JS动态加载JS文件

直接document.write

1
2
3
<script language="javascript">
document.write("<script src='test.js'><\/script>");
</script>

动态改变已有script的src属性

1
2
3
4
5
<script src='' id="s1"></script>
<script language="javascript">
var scriptE=document.getElementById("s1");
scriptE.src="test.js"
</script>

动态创建script元素

1
2
3
4
5
6
7
<script>
var headDom = document.getElementsByTagName('HEAD').item(0);
var scriptDom= document.createElement("script");
scriptDom.type = "text/javascript";
scriptDom.src="test.js";
headDom.appendChild(scriptDom);
</script>

使用jQuery

使用getScript(url,callback)方法实现动态加载js文件

1
2
3
$.getScript('test.js',function(){
alert('done');
});

参考资料

https://www.jb51.net/article/17992.htm
https://www.jb51.net/article/139481.htm