方法一:原生
adc.js內容如下:
var hello = "H9";
html.html
<script>
var s = document.createElement("script");
s.src = "abc.js";
document.head.appendChild(s);
s.addEventListener("load",function(){
// 等待s的load事件加載完響應,防止未加載完就調用出錯
console.log(hello);
})
setTimeout(function(){//或者使用定時器保證其載入完後調用(不安全,不如監聽事件好)
console.log(hello);
},1000);
// $.getScript("abc.js");
</script>
方法二:jquery.js
$.getScript("abc.js",function(){ alert("heheheh"); console.log(hello); });
<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">
$(function()
{
$('#loadButton').click(function(){
$.getScript('new.js',function(){
newFun('"Checking new script"');//這個函數是在new.js裡面的,當點擊click後運行這個函數
});
});
});
</script>
</head>
<body>
<button type="button" id="loadButton">Load</button>
方法三:require.js
require.js分享2.1.1版本,注意是針對大項目使用,一邊情況下使用jquery即可。
index.html
<!--設置入口文件main 可以省略js-->
<script data-main="main" src="require.js"></script>
main.js
console.log("你好世界");
require(["js1","js2","js3"],function () {
// 是異步加載導入。js後綴可以省略
console.log("你們加載完了麼?");
var total = num1+num2+num3;
console.log(total);
hello1();
hello2();
hello3();
})
使用requireJs可以很方便的導入js文件,但是要注意js文件中變量名方法名沖突的問題。 產生原因:浏覽器js文件共用全局作用域,作用域中變量名方法名可能被覆蓋