I’m trying to optimize the javascript on my website. I was surprised by my findings and wanted to have someone else look at what I did to see if something is skewing my results or i’m interpreting it wrong.
This is the old way I use to load my javascript:
<script type="text/javascript">
var GB_ANIMATION = true;
var beginExecCount = new Date().getTime(); //Timer Start
</script>
<script type="text/javascript" src="js/jquery.js" ></script>
<script type="text/javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" src="js/views.js"></script>
<script type="text/javascript" src="js/main.js" ></script>
<script type="text/javascript" src="js/greybox.js"></script>
<script type="text/javascript">
initViews();
alert((new Date().getTime()) - beginExecCount); //Print total elapsed time
</script>
</body>
In this method I had all my javascripts linked before the body element. After the scripts were loaded I initialize the page. You will also see 2 lines which I used to measure the load time in miliseconds.
This is my new method for loading javascript:
<script type="text/javascript">
var GB_ANIMATION = true;
var beginExecCount = new Date().getTime();
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);
}
loadScript("js/jquery.js", function(){
loadScript("js/jquery.dataTables.js", function(){
loadScript("js/views.js", function(){
loadScript("js/main.js", function(){
initViews();
loadScript("js/greybox.js", function(){
});
});
});
});
});
</script>
<script type="text/javascript">
alert((new Date().getTime()) - beginExecCount);
</script>
</body>
This method instead relies on a simple script to load the scripts in a waterfall fashion. The initialization function is then called after the first 4 are loaded and before the last. Once again I used the same timing methods at the beginning and end.
My Results (Firefox 3.6.11):
Method 1: 65+99+94+91+112+148+170+90+111+88 = 1068/10 = 106.8ms
Method 2: 1021+1037+1057+1032+1036+1057+1038+1017+1024+1028 = 10347/10 = 1034.7ms
My questions:
- Is there a more reliable way for timing the time it takes to execute a segment of code? The way I did it was I refreshed the page 10 times recording the values for each refresh and then calculating the average.
- Are my findings accurate with your experience? Or is something else going on here? The reason I ask is I expected an increase in reliability do to the waterfall-style loading. What I did not expect was such a large change in loading time.
- Any other suggestions for optimizing the loading of javascript files?
Thanks for your input!