Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to defer loading of jQuery?

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 some tabs which are placed low on the page (mostly out of initial view) and I'd like to defer jQuery until AFTER the page has rendered.

Google's deferral code adds a tag to the DOM after the page loads by hooking into the body onLoad event:

<script type="text/javascript">   // Add a script element as a child of the body  function downloadJSAtOnload() {  var element = document.createElement("script");  element.src = "deferredfunctions.js";  document.body.appendChild(element);  }   // Check for browser support of event handling capability  if (window.addEventListener)  window.addEventListener("load", downloadJSAtOnload, false);  else if (window.attachEvent)  window.attachEvent("onload", downloadJSAtOnload);  else window.onload = downloadJSAtOnload;  </script> 

I'd like to defer loading of jQuery this way, but when I tried it my jQuery code failed to find jQuery (not completely unexpected on my part):

$(document).ready(function() {     $("#tabs").tabs(); }); 

So, it seems I need to find a way to defer execution of my jQuery code until jQuery is loaded. How do I detect that the added tag has finished loading and parsing?

As a corollary, it appears that asynchronous loading may also contain an answer.

Any thoughts?

like image 456
Kevin P. Rice Avatar asked May 02 '11 01:05

Kevin P. Rice


People also ask

Can jQuery be deferred?

This JQuery. Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.

Should jQuery be async or defer?

For example, if you're using jQuery as well as other scripts that depend on it, you'd use defer on them (jQuery included), making sure to call jQuery before the dependent scripts. A good strategy is to use async when possible, and then defer when async isn't an option.

How do you defer in JavaScript?

Definition and UsageIf the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).

What do we achieve by deferring the loading of JavaScript?

Overview. Deferring loading of JavaScript functions that are not called at startup reduces the initial download size, allowing other resources to be downloaded in parallel, and speeding up execution and rendering time.


2 Answers

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         }) }); 
like image 56
ampersand Avatar answered Oct 19 '22 03:10

ampersand


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<dfGroup.length; i++) {         dfLoadStatus++;         var element = document.createElement('script');         element.src = dfGroup[i];         element.onload = element.onreadystatechange = function() {         if ( ! this.readyState ||                 this.readyState == 'complete') {             dfLoadStatus--;             if (dfLoadStatus==0) downloadJSAtOnload();         }     };     document.body.appendChild(element);   }  }  if (window.addEventListener)     window.addEventListener("load", downloadJSAtOnload, false); else if (window.attachEvent)     window.attachEvent("onload", downloadJSAtOnload); else window.onload = downloadJSAtOnload; 

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"]); 
like image 24
Pevawi Avatar answered Oct 19 '22 04:10

Pevawi