Best way to load your JavaScript

via Ajaxian » Front Page by Dion Almaer on 7/30/09

Nicholas Zakas thinks he has the best way to load JavaScript.

Steve Souders has a bunch of best practices, and it seems that there is definitely nuance that makes advice very much tailored to your circumstance.

Nicholas though, has an opinion:

I’ve come to the conclusion that there’s just one best practice for loading JavaScript without blocking:

  1. Create two JavaScript files. The first contains just the code necessary to load JavaScript dynamically, the second contains everything else that’s necessary for the initial level of interactivity on the page.
  2. Include the first JavaScript file with a <script> tag at the bottom of the page, just inside the </body>.
  3. Create a second <script> tag that calls the function to load the second JavaScript file and contains any additional initialization code.

A helper to make this happen could look like:

JAVASCRIPT:
  1.  
  2. function loadScript(url, callback){
  3.  
  4.     var script = document.createElement("script")
  5.     script.type = "text/javascript";
  6.  
  7.     if (script.readyState){  //IE
  8.         script.onreadystatechange = function(){
  9.             if (script.readyState == "loaded" ||
  10.                     script.readyState == "complete"){
  11.                 script.onreadystatechange = null;
  12.                 callback();
  13.             }
  14.         };
  15.     } else {  //Others
  16.         script.onload = function(){
  17.             callback();
  18.         };
  19.     }
  20.  
  21.     script.src = url;
  22.     document.getElementsByTagName("head")[0].appendChild(script);
  23. }
  24.  

In related news, the LABjs folk have updated their API from this:

JAVASCRIPT:
  1.  
  2. $LAB
  3. .script("jquery.js")
  4. .block(function(){
  5.       $LAB
  6.       .script("jquery.ui.js")
  7.       .script("myplugin.jquery.js")
  8.       .block(function(){
  9.             $LAB.script("initpage.js");
  10.       });
  11. });
  12.  

to the simpler:

JAVASCRIPT:
  1.  
  2. $LAB
  3. .script("jquery.js")
  4. .block()
  5. .script("jquery.ui.js")
  6. .script("myplugin.jquery.js")
  7. .block()
  8. .script("initpage.js");
  9.  

I seem to remember that Steve had some opinions on this API too :)

Loading mentions Retweet
Filed under  //   javascript   programming  

Comments (1)

Jul 31, 2009
Lukasz Korecki said...
Just tested e-mail posting from Google Reader.
Looks good :-)

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    twitter


 

About

http://coffeesounds.com
Webdev, coffee drinker and all that