脚本的加载会阻塞页面其他文件的下载,采用以下办法进行优化:
一. 组织脚本
a、将多个脚本文件整合(减少HTTP请求)b、将script标签放置在页面文件的底部(页面加载完成后加载)
二. 无阻塞脚本
即页面加载完成后再加载js代码
三. 延迟脚本
在script标签中使用defer属性(不推荐)
四. 动态脚本元素(文件的加载与执行不会阻塞页面其他进程)
<html>
<head>
<title></title>
<script type="text/javascript">
function init()
{
var myScript= document.createElement("script");
myScript.type = "text/javascript";
myScript.onload = function(){
alert("Script 加载已完成!")
}
myScript.src="package.js";
document.body.appendChild(myScript);
//如果马上使用会找不到,因为还没有加载进来
functionOne();
}
function operation()
{
//可以运行,显示“成功加载”
functionOne();
}
</script>
</head>
<body>
<input type="button" value="测试按钮" onclick="init()"/>
<input type="button" value="测试运行效果" onclick="operation()"/>
</body>
</html>
五. 推荐的无阻塞模式
1.先添加动态加载需要的代码 主要包含load_script()函数
function load_script(xyUrl, callback){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = xyUrl;
//借鉴了jQuery的script跨域方法
script.onload = script.onreadystatechange = function(){
if((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")){
callback && callback();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
head.insertBefore( script, head.firstChild );
}
2.使用构建的加载器加载
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript" >
load_script("the-rest.js",function(){
Application.init();
})
</script>
3.LazyLoad类库是load_script()函数的增强版
六、模块引用
sea.js与requier.js都是在执行到引用代码,再下载(按需加载)