<script>标签会阻塞页面的解析过程,新的浏览器已经充许<script>标签之间可以并行下载,但仍然会阻塞其它资源的下载
Nonblocking Scripts
1.Deferred Scripts
<scripttype="text/javascript" src="file1.js" defer></script>
ie支持。
一个带有defer属性的<script>标签可以放置在文档的任何位置。对应的JavaScript 文件将在<script>被解析
时启动下载,但代码不会被执行,直到DOM加载完成(在onload 事件句柄被调用之前)
2.DynamicScript Elements
<script>和普通dom元素一样,可以被动态创建。用这种方法生成的<script>不会阻塞页面的解析过程
<script>的状态
Uninitialized
Loading
Loaded
Interactive
Complete
这些状态不一定全部出现
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 {
script.onload = function() {
callback();
}
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
3.XMLHttpRequestScript Injection
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);