Lazily加载CSS和JS

时间:2014-09-12 13:10:12

标签: javascript css lazy-loading

我已经编写了这段JS和CSS加载代码,我想要一些建议。一些Javascript Gurus可能指出的任何东西都会非常感激。代码有效,但我没有做过大量的测试,因为我担心以这种方式替换函数。

包含JQuery的单个javascript文件以及以下代码将包含在所有页面中。我们在内部编写所有组件并将它们保持非常模块化,并使用相应的JS和CSS分隔到它们自己的文件夹中。你可以想象开始使用例如一个页面上的dropown,对话框和一个datepicker将要求我们添加6个包含,这非常令人讨厌,因为我希望依赖项自动解决并且使用JSP包含可能会多次调用相同的资源。

下面是懒惰加载单个日期选择器的src

;(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;
}

1 个答案:

答案 0 :(得分:1)

您是否查看了Require JS,它将仅针对给定模块发送所需模块的异步请求。

此外,由于依赖关系是作用于回调函数的,因此命名空间冲突不是问题

通常你会:

require(["jquery", "foo", "bar"], function($, foo, bar){...});

允许您的代码在不同的位置保持模块化服务器端和客户端。

当然,您需要在服务器上使用配置(在网页中描述)设置require,并将资源包装在define块中:

define("foo", ["jquery"], function($){...});

缺点是需要许多模块的页面的性能。在这种情况下,您可以从组合文件中的所有资源中获益更多,但请注意,查询字符串将导致浏览器在任何情况下都不会缓存文件。这也是另一个性能考虑因素。

希望有所帮助

PS。在CSS延迟加载方面,您总是可以使用javascript将链接标记注入头部adhoc,并提供一些其他代码可以调用的javascript接口函数,以便动态请求CSS依赖。