1、延迟解析
<script type="text/javascript" src="file1.js" defer></script> defer告诉解析器该脚本不会修改Dom,可以迟点再解析执行
也可以写在网页内脚本
<script defer>
alert("defer");
</script>
2、动态生成脚本连接
function loadScript(url, callback){
var script = document.createElement("script"),
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
使用方式:
loadScript("file1.js", function(){
loadScript("file2.js", function(){ //这里动态加载了三个脚本,注意加载的顺序,Firefox和opera会按你写的顺序执行,而有些浏览器则是按照它们从服务器返回的顺序执行
loadScript("file3.js", function(){
alert("All files are loaded!");
});
});
});
3、ajax 脚本注入
var xhr = new XMLHttpRequest();
xhr.open("get", "file1.js", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
var script = document.createElement("script");
script.type = "text/javascript";
script.text = xhr.responseText;
document.body.appendChild(script);
}
}
};
xhr.send(null);
推荐的模式(第二种),在页面里写动态生成脚本的函数,再动态加载可以延迟执行的脚本
<script type="text/javascript">
function loadScript(url, callback) {
var script = document.createElement("script"),
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript("the-rest.js", function(){
Application.init();
});
</script>