如何动态加载JavaScript文件?

如何动态加载JavaScript文件?,第1张

如何动态加载JavaScript文件

您不能以这种方式将HTML嵌入Javascript。基本上,您想要的是嵌入一个脚本元素,单击按钮时指向某个javascript文件。可以通过将事件与DOM结合来完成:

<script type="application/javascript">function loadJS(file) {    // DOM: Create the script element    var jsElm = document.createElement("script");    // set the type attribute    jsElm.type = "application/javascript";    // make the script element load file    jsElm.src = file;    // finally insert the element to the body element in order to load the script    document.body.appendChild(jsElm);}</script><button onclick="loadJS('file1.js');">Load file1.js</button><button onclick="loadJS('file2.js');">Load file2.js</button>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5629904.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存