Best way to load your JavaScript ...

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 tag at the bottom of the page, just inside.
3. Create a second 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:

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

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


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

To the simpler:


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

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

If you have better solution, just tell me !

0 comments: