Possible to defer loading of jQuery?

前端 未结 16 1149
孤街浪徒
孤街浪徒 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 19:41

    In certain situation you could fire an event when jquery is loaded.

    
    

    Then wrap your dependencies in a function:

    // myscript1.js 
    (function(){ 
    
        function initMyjQueryDependency() {
            console.log('my code is executed after jquery is loaded!');
            // here my code that depends on jquery
        }
    
        if ( jQueryHasLoaded === true )
            initMyjQueryDependency();
        else
            document.body.addEventListener('jqueryloaded', initMyjQueryDependency, false);
    
    }());
    

    If jquery finishes to load after the other scripts, your dependencies will be executed when the jqueryloaded event is fired.

    If jquery is already loaded, jQueryHasLoaded === true, your dependency will be executed initMyjQueryDependency().

提交回复
热议问题