您的位置:首页 > Web前端 > JavaScript

[Web] 被遗忘的知识点 - JavaScript加载管理最佳实践

2013-03-06 15:23 495 查看
前言

最近项目有一个需求,如下: HTML页面一般来说可以由CSS、JavaScript、Dom(通常为Div)以及一些JS初始化页面函数组成,现在需要将一个页面拆分为CSS、JavaScript、Dom和JS init函数四部分,通过从服务端分别获取这四部分,经过拼凑后,渲染出完整的页面。这里面CSS、DOM节点比较好处理,但是JavaScript的加载以及JS init的执行,就要考虑到很多问题。如果有谁遇到类似的问题,可以讨论下,毕竟想要将这个做成一个完善的框架会遇到很多问题。这篇文章,我将介绍一些加载管理JavaScript的一些实践,希望对你有所帮助。

原生的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);
}


LAB实现

$LAB.setOptions({
AlwaysPreserveOrder: true
})
.script("script1.js") // script1, script2, script3, and script4 *DO* depend on each
.script("script2.js") // other, and will execute serially in order after all 4 have have
.script("script3.js") // loaded in parallel
.script("script4.js")
.wait(function () {
initFunction();
});


$LAB.setOptions({
AllowDuplicates: true
})
.script("script1.js").wait()
.script("script2.js")
.script("script3.js").wait()
.script("script4.js")
.wait(function () {
initFunction();
});


RequireJS实现

(function (require) {

var urlArgs = ''; // used for browser cache
if (CNBlogs.isProduct) {
urlArgs = 'v=1';
} else {
urlArgs = "dev=" + (new Date()).getTime();
}

require.config({
baseUrl: '/scripts', //By default load any module IDs from baseUrl
urlArgs: urlArgs,
paths: {
'hello1': 'hello1.min',
'hello2': '/document/11111-11100-010101/latest?' // append ? to avoid .js extension
},
shim: {
'hello3': ['hello1', 'hello2'],
'hello4': ['hello3', 'bootstrap']
},
waitSeconds: 200
});

})(require);

require(['jqueryui', 'hello4'], function () {
initFunction();
});


参考文档

LABJS官网文档: http://labjs.com/documentation.php
RequireJS官网文档: http://requirejs.org/docs/api.html
后续

LABJS和RequireJS没有绝对的好差,只看你使用哪一种比较方便而已,这篇文章中很多问题没有细细说明,如果有疑问可以联系,相互探讨。

QQ: 1321518080
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: