Defer loading of javascript
by Francis[ Edit ] 2013-12-17 09:56:35
Defer loading of javascript
Defer JavaScript tries to defer JavaScript execution until page load. So we could push below code at bottom of page, that is above of body (</body>) tag close.
code
Type 1
Normal Script to add your javascript
<script type="text/javascript">
// Add a script element as a child of the body
function downloadJSAtOnload()
{
var srcList = new Array("js/jquery.js","js/other.js");
for(inc=0;inc<srcList.length;inc++)
{
var element = document.createElement("script");
element.src = srcList[inc];
document.body.appendChild(element);
}
}
// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
Type 2
Set priority to the javascript, which one first take to complete. Following Code to explain the jquery.js first execute and then take other javascript files.
<script type="text/javascript">
var dfLoadStatus = 0;
var dfLoadFiles = [
["js/jquery.js"],
["js/other1.js", "js/other2.js", "js/other3.js"]
];
function downloadJSAtOnload()
{
if (!dfLoadFiles.length) return;
var dfGroup = dfLoadFiles.shift();
dfLoadStatus = 0;
for(var i = 0; i<dfGroup.length; i++) {
dfLoadStatus++;
var element = document.createElement('script');
element.src = dfGroup[i];
element.onload = element.onreadystatechange = function() {
if ( ! this.readyState ||
this.readyState == 'complete' || this.readyState == 'loaded') {
dfLoadStatus--;
if (dfLoadStatus==0) downloadJSAtOnload();
}
};
document.body.appendChild(element);
}
}
// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>