Search

8/04/2009

Best way to load your JavaScript

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 <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.

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);
}


<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
//initialization code
});
</script>


What if your page requires more than two files? Then you should be concatenating your files together either at build time (using something like Sprockets) or at run time (using something like mod_concat or a combo handler).

沒有留言: