一、代码示例:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>动态加载JS文件</title>
</head>
<body>
<button id="btn" onclick="loanScript('test.js'),callback">加载js文件</button>
<script type="text/javascript"> function callback(){
console.log("script load complete");
loadSuccess();
}
function loanScript(url,callbackFun){
var script = document.createElement("script");
script.type = "text/javascript";
//兼容IE浏览器
if(script.readyState){
script.onreadystatechange = function(){
if(script.readyState == "loaded" || script.readyState == "complete"){
script.onreadystatechange = null;
callbackFun();
}
}
}else{//其他浏览器
script.onload = function(){
callbackFun();
}; } script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
</script>
</body>
</html>
注意除了Firefox和Opera保证脚本文件按照代码顺序加载,其他浏览器不保证文件按照你指定的顺序加载,可通过串联操作保证文件的加载次序代码如下
window.onload=function(){
loadScript("file1.js",function(){
loadScript("file2.js",function(){
loadScript("file3.js",function(){
alert("all js document are loaded");
});
});
}); }