Possible to defer loading of jQuery?

前端 未结 16 1150
孤街浪徒
孤街浪徒 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:39

    Try this, which is something I edited a while ago from the jQuerify bookmarklet. I use it frequently to load jQuery and execute stuff after it's loaded. You can of course replace the url there with your own url to your customized jquery.

    (function() {
          function getScript(url,success){
            var script=document.createElement('script');
            script.src=url;
            var head=document.getElementsByTagName('head')[0],
                done=false;
            script.onload=script.onreadystatechange = function(){
              if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
                done=true;
                success();
                script.onload = script.onreadystatechange = null;
                head.removeChild(script);
              }
            };
            head.appendChild(script);
          }
            getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',function(){
                // YOUR CODE GOES HERE AND IS EXECUTED AFTER JQUERY LOADS
            });
        })();
    

    I would really combine jQuery and jQuery-UI into one file and use a url to it. If you REALLY wanted to load them separately, just chain the getScripts:

    getScript('http://myurltojquery.js',function(){
            getScript('http://myurltojqueryUI.js',function(){
                  //your tab code here
            })
    });
    

提交回复
热议问题