Possible to defer loading of jQuery?

前端 未结 16 975
孤街浪徒
孤街浪徒 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.

    <script type="text/javascript">
        (function (window) {
    
            window.jQueryHasLoaded = false;
    
            document.body.addEventListener('jqueryloaded', function (e) {
                console.log('jqueryloaded ' + new Date() );
            }, false);
    
            function appendScript(script) {
                var tagS = document.createElement("script"), 
                    s = document.getElementsByTagName("script")[0];
                tagS.src = script.src;
                s.parentNode.insertBefore(tagS, s);
    
                if ( script.id == 'jquery' ) {
                    tagS.addEventListener('load', function (e) {
                        window.jQueryHasLoaded = true;
                        var jQueryLoaded = new Event('jqueryloaded');
                        document.body.dispatchEvent(jQueryLoaded);
                    }, false);
                }
            }
    
            var scripts = [
                {
                    'id': 'jquery',
                    'src': 'js/libs/jquery/jquery-2.0.3.min.js'
                },
                {
                    'src': 'js/myscript1.js'
                },
                {
                    'src': 'js/myscript2.js'
                }
            ];
    
            for (var i=0; i < scripts.length; i++) {
                appendScript(scripts[i]);
            }
    
        }(window));
    </script>
    

    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().

    0 讨论(0)
  • 2020-11-28 19:43

    Load all scripts at the end of html with http://labjs.com, it is 100% solution and I tested it many times against gtmetrix rules. example http://gtmetrix.com/reports/interactio.cz/jxomHSLV

    0 讨论(0)
  • 2020-11-28 19:50

    Here is a good description of modern approach for async/defer javascript loading. But it doesn't works for inline scripts

    <script type="text/javascript" src="/jquery/3.1.1-1/jquery.min.js" defer></script>
    <script type="text/javascript" defer>
        $(function () {   //  <- jquery is not yet initialized
          ...
        });
    </script>
    

    The simplest solution for async loading was suggested by @nilskp - externalize script:

    <script type="text/javascript" src="/jquery/3.1.1-1/jquery.min.js" defer></script>
    <script type="text/javascript" src="resources/js/onload.js" defer></script>
    
    0 讨论(0)
  • 2020-11-28 19:54

    I think Modernizr.load() is worth a mention here - it handles dependency loading very nicely

    0 讨论(0)
  • 2020-11-28 19:55
    element.addEventListener("load", function () {
        $('#tabs').tabs()
    }, false);
    

    Try that.

    0 讨论(0)
  • 2020-11-28 19:55

    I add this piece of code after the async/defered jquery script tag, this defines a temporary function $ that will accumulate whatever it is that needs to run when everything is done loading, and then once we're done use $ that by this time would be overwritten to execute the functions. With this piece of code there's no need to change the jQuery onload syntax further down in the document.

    <script defer async src="https://code.jquery.com/jquery-2.2.0.min.js">
    <script>
        var executeLater = [];
        function $(func) {
            executeLater.push(func);
        }
        window.addEventListener('load', function () {
            $(function () {
                for (var c = 0; c < executeLater.length; c++) {
                    executeLater[c]();
                }
            });
        })
    </script>
    

    ....and then...

    <script>
        $(function() {
            alert("loaded");
        });
    </script>
    
    0 讨论(0)
提交回复
热议问题