我写过这段JS和CSS加载代码,我希望对它有一些建议。任何一些Javascript大师可能会指出的东西将非常感激。代码有效,但我没有做过广泛的测试,因为我担心以这种方式替换函数。Lazily加载CSS和JS
包含JQuery的单个JavaScript文件以及下面的代码将包含在所有页面中。我们在内部编写所有组件,并使用相应的JS和CSS将它们保持模块化,并将它们分离到各自的文件夹中。你可以想象开始在一个页面上使用dropown,dialog和datepicker会要求我们添加6个包含,这很坦率地令人讨厌,因为我想依赖关系自动解析,并且使用JSP包含可能会多次调用相同的资源。
下面是加载一个日期选择器懒洋洋地
;(function($){
//All Lazily loaded components go here
$.fn.datepicker = function(settings){
console.log("This should only be displayed once");
loadCSS("/res/component/datepicker/datepicker.css");
var elem = this;
return loadJS("/res/component/datepicker/datepicker.js",
function(){return elem.datepicker(settings)});//After Load Completion the $.fn.datepicker is replaced
//by the proper working implementation, execute it and return it so we maintain the chain
};
}(jQuery));
function loadCSS(absoluteUrl){
if(loadCSS[absoluteUrl])
return;//Css already loaded
$('<link>')
.appendTo('head')
.attr({type : 'text/css', rel : 'stylesheet'})
.attr('href', absoluteUrl);//Appending entire element doesn't load in IE, but setting the href in this manner does
loadCSS[absoluteUrl] = true;//Memoize
}
function loadJS(absoluteUrl, onComplete){
if(loadJS[absoluteUrl])
return;//Script already loaded
loadJS[absoluteUrl] = true;//Memoize
var result;
jQuery.ajax({
async : false,//Synchronized because we need to maintain the JQuery chain
type :'GET',
url : absoluteUrl,
dataType :'script',
success : function(){
result = onComplete();
}
});
return result;
}
这个问题似乎是题外话题,因为它更适合http://codereview.stackexchange.com/ – Andy 2014-09-12 13:12:27
为什么你滚动你自己?因为你不知道像RequireJS这样的东西,或者你想学习,或者因为所有现有的解决方案都不够好,......?我问,因为我试图做同样的事情(“学习”),但我真的学会了如何在开始使用现有库(准确地说是RequireJS)时正确设置模块化应用程序。 – Gimby 2014-09-12 14:16:42
我滚动自己的原因是因为我的需求非常具体,因此提供了代码片段。它完全符合我的要求,而且非常简约。所有其他提到的点仅仅是好处。依靠别人的代码几乎总是让我头痛得多,而不是解决问题,无论是需要维护代码的授权问题还是浏览器支持问题。如果中断,我可以修复它的类型。 – 2014-09-12 14:47:34