Possible to defer loading of jQuery?

前端 未结 16 1155
孤街浪徒
孤街浪徒 2020-11-28 19:26

Let\'s face it, jQuery/jQuery-ui is a heavy download.

Google recommends deferred loading of JavaScript to speed up initial rendering. My page uses jQuery to set up s

16条回答
  •  佛祖请我去吃肉
    2020-11-28 20:00

    As this is a top ranking question on a important subject let me be so bold to provide my own take on this based on a previous answer from @valmarv and @amparsand.

    I'm using a multi-dimensional array to load the scripts. Grouping together those that have no dependencies between them:

    var dfLoadStatus = 0;
    var dfLoadFiles = [
          ["http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"],
          ["http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js",
           "/js/somespecial.js",
           "/js/feedback-widget.js#2312195",
           "/js/nohover.js"]
         ];
    
    function downloadJSAtOnload() {
        if (!dfLoadFiles.length) return;
    
        var dfGroup = dfLoadFiles.shift();
        dfLoadStatus = 0;
    
        for(var i = 0; i

    It loads first jquery after it is loaded it continue to load the other scripts at once. You can add scripts easy by adding to the array anywhere on your page:

    dfLoadFiles.push(["/js/loadbeforeA.js"]);
    dfLoadFiles.push(["/js/javascriptA.js", "/js/javascriptB.js"]);
    dfLoadFiles.push(["/js/loadafterB.js"]);
    

提交回复
热议问题