Jul 31
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:
- 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.
- Include the first JavaScript file with a
<script>tag at the bottom of the page, just inside the</body>.- 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:
-
- function loadScript(url, callback){
-
- var script = document.createElement("script")
- script.type = "text/javascript";
-
- if (script.readyState){ //IE
- script.onreadystatechange = function(){
- if (script.readyState == "loaded" ||
- script.readyState == "complete"){
- script.onreadystatechange = null;
- callback();
- }
- };
- } else { //Others
- script.onload = function(){
- callback();
- };
- }
-
- script.src = url;
- document.getElementsByTagName("head")[0].appendChild(script);
- }
-
In related news, the LABjs folk have updated their API from this:
JAVASCRIPT:
-
- $LAB
- .script("jquery.js")
- .block(function(){
- $LAB
- .script("jquery.ui.js")
- .script("myplugin.jquery.js")
- .block(function(){
- $LAB.script("initpage.js");
- });
- });
-
to the simpler:
JAVASCRIPT:
-
- $LAB
- .script("jquery.js")
- .block()
- .script("jquery.ui.js")
- .script("myplugin.jquery.js")
- .block()
- .script("initpage.js");
-
I seem to remember that Steve had some opinions on this API too :)
Filed under //
javascript
programming

Looks good :-)