Load JavaScript after pageload

loading JavaScript after page load
The most common reason that website don’t rank good in popular web sites is slower loading time. Often excessive JavaScript on your page is the main reason for this. The page has either too much of JavaScript code or it refers to a lot of third party JavaScript files from different servers (like advertisement server or any other third party widgets you are using).
In this post we will discuss various approaches for delaying JavaScript loading till content on your page loads.

One of the simplest solutions for this problem is to put all of your JavaScript code at the end of HTML page. This will make content on site to load earlier and then Script may load while user is going through contents of your website.

Using defer attribute:

Placing defer attribute in your script tag will ensure the halting of loading and execution of script till page is loaded and ready.

But, bottleneck of this method is it works only with Internet Explorer. So, for the rest of 70% users the result will be same as before.
Dynamically Insert References:

Inserting JavaScript references after content load will force script loading after content. On Onload () event of a page you can insert a function that will automatically assign references to the missing JavaScript files.
For Example.

function afterLoad(){
var element1 = document.createElement(“script”);
element1.src = “somefile.js”;
element1.type=”text/javascript”;
document.getElementsByTagName(“head”)[0].appendChild(element1);
}

This works well, except that widgets will be still loaded in the order that is included in afterLoad() function, and if one blocked, all the others would wait, this will result in to waiting icon on your browser tab even if all the content is loaded on page. So, there is need to make things load asynchronously. This can be achieved through setting async attribute to true. Adding the below line to afterLoad() function will ensure that widgets load in parallel independent of others.

element1.async=true;

Using jQuery:
If you want to ensure that even content like images have loaded first, plus you want to ease out cross browser code compatibility issues, then jQuery library will make made your life easy with functions $(window).load() and $.getScript().

$(window).load( function() {
$.getScript(‘your_3rd_party-script.js’);
});

Before loading your custom jQuery function you need to include CSS style sheet and jQuery.js file.


$(window).load( function() {
$.getScript(‘your_3rd_party-script.js’);
});

Dealing with document.write and document.writeln:

If you have document.write in any of script files then above methods won’t work. So, a different approach is needed to deal with document.write

(function() {
Scrpt = window.Scrpt || {};
var _write = document.write;
var _writeln = document.writeln;
document.writeln = document.write = function(s) {
var id=”;
if(s.match(/\widget_1/)) {
id=’Widget1_wrapper’;
}
else if(s.match(/\widget_2\/)) {
id=’Widget2_wrapper’;
}
else {
id=’overflow_div’;
//_write(s);
}
Scrpt.onavailable(id, function(el) { el.innerHTML = s; });
return true;
};
Scrpt.onavailable = function(id, fn) {
var el = document.getElementById(id);
if(!el) {
window.setTimeout(function() { Scrpt.onavailable(id, fn); id=fn=null; }, 100);
return;
}
fn(el);
};
Scrpt.load = function(s, code) {
var e = document.createElement(‘script’);
e.type = ‘text/javascript’;
e.src=s;
if(code) {
e.onreadystatechange = function() { if(e.readyState == ‘complete’) code(); };
e.onload = code;
}
document.getElementsByTagName(‘head’)[0].appendChild(e);
};})();

All the JavaScript code can be aggregated at bottom of page and it is loaded dynamically by comparing div ids of respective divs. The attribute onreadystatechange ensures the scripts loaded asynchronously.

Do you like this article or want to say “Hi” to author? Note it down in comments.
  • http://www.yamaha660grizzly.com/ Dokemion

    I'm just browsing the web trying to gather some information before my java training next week. Thanks for this post.

  • Jazzie

    I’m just browsing the web trying to gather some information before my Java training next week. Thanks for this post.

  • http://rajab.se/ Usman Rajab

    Like tiger said: It´s Grrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeaaaatttttttttttt! nice post!

  • Fuck

    garbage.. maybe this would have helped like pre-jquery..
    come on get it together

  • http://twitter.com/WordImpressed Devin Walker

    Extremely well written article and I am using the jQuery tid bit!

  • http://rajab.se/ Usman Rajab

    Like tiger said: It´s Grrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeaaaatttttttttttt! nice post!

    • http://www.tutkiun.com/ Mayur

      Thank you! :)

  • Fuck

    Great Info! Thanks!

  • cheapsally

    Extremely well written article and I am using the jQuery tid bit!

    • http://www.tutkiun.com/ Mayur

      Thanks Devin. jQuery make one’s job easy, by eliminating all cross browser compatibility issues.

  • http://mathiasbynens.be/ Mathias

    “But, bottleneck of this method is it works only with Internet Explorer. So, for the rest of 70% users the result will be same as before.”

    That’s not true, Mozilla has supported the `defer` attribute since Firefox 3.

  • http://mathiasbynens.be/ Mathias

    “But, bottleneck of this method is it works only with Internet Explorer. So, for the rest of 70% users the result will be same as before.”

    That’s not true, Mozilla has supported the `defer` attribute since Firefox 3.

    • nathankleyn

      Not only that, but at last count, IE represents ~50% market share, which means with Firefox support, only ~10% of visitors will not get the deferred script behaviour.

      Makes it definitely worth the effort now. =]

    • Prakash

      got it man………..

  • http://twitter.com/shimmyohana shimmy ohana

    Mayur – great article! this is what we call thinking out of the box

  • http://twitter.com/shimmyohana shimmy ohana

    Mayur – great article! this is what we call thinking out of the box

    • http://www.tutkiun.com/ Mayur

      Thanks Shimmy. Hope you like others as well

  • http://www.onlythebible.com Eman

    Love your search feature!
    Great site.

  • http://www.onlythebible.com Eman

    Love your search feature!
    Great site.

    • http://www.tutkiun.com/ Mayur

      Thanks..

  • http://skybondsor.com/ skybondsor

    Thanks for this! Twitter was totally gumming up my works.

  • http://www.tutkiun.com/ Mayur

    Thanks Devin. jQuery make one's job easy, by eliminating all cross browser compatibility issues.

  • http://www.tutkiun.com/ Mayur

    Thank you! :)

  • http://www.tutkiun.com/ Mayur

    You are welcome man

  • http://www.tutkiun.com/ Mayur

    Thanks..

  • http://www.tutkiun.com/ Mayur

    Thanks Shimmy. Hope you like others as well

  • http://skybondsor.com/ skybondsor

    Thanks for this! Twitter was totally gumming up my works.

    • http://www.tutkiun.com/ Mayur

      You are welcome man

  • http://www.sareez.com/ sarees

    great…

  • http://www.sareez.com/ sarees

    great…

  • Ammy_769

    Amazing post..Well written…Keep it up.

  • Ammy_769

    Amazing post..Well written…Keep it up.

  • http://twitter.com/unfinitydesign Nathan Kleyn

    Not only that, but at last count, IE represents ~50% market share, which means with Firefox support, only ~10% of visitors will not get the deferred script behaviour.

    Makes it definitely worth the effort now. =]

  • http://twitter.com/wedocando Ben McLardy

    Thanks Mayur! The jQuery snippet helped me tidy up my markup!

  • http://twitter.com/wedocando Ben McLardy

    Thanks Mayur! The jQuery snippet helped me tidy up my markup!

  • Prakash

    got it man………..

  • Pingback: Sleep mode for websites | Tutkiun!

  • Anonymous

    ok

  • maccicchitte

    ok

  • The Pc Recycler

    i hate programmers

  • BikkY Sah

    I have

    <script type=’text/javascript’>var relatedpoststitle=&quot; &quot;;</script>
    <script type=’text/javascript’>/*<![CDATA[*/var relatedTitles=new Array();var relatedTitlesNum=0;var relatedUrls=new Array();function related_results_labels(g){for(var h=0;h<g.feed.entry.length;h++){var f=g.feed.entry[h];relatedTitles[relatedTitlesNum]=f.title.$t;for(var i=0;i<f.link.length;i++){if(f.link[i].rel=="alternate"){relatedUrls[relatedTitlesNum]=f.link[i].href;relatedTitlesNum++;break}}}}function removeRelatedDuplicates(){var g=new Array(0);var f=new Array(0);for(var e=0;e<relatedUrls.length;e++){if(!contains(g,relatedUrls[e])){g.length+=1;g[g.length-1]=relatedUrls[e];f.length+=1;f[f.length-1]=relatedTitles[e]}}relatedTitles=f;relatedUrls=g}function contains(a,e){for(var g=0;g<a.length;g++){if(a[g]==e){return true}}return false}function printRelatedLabels(e){for(var g=0;g<relatedUrls.length;g++){if(relatedUrls[g]==e){relatedUrls.splice(g,1);relatedTitles.splice(g,1)}}var f=Math.floor((relatedTitles.length-1)*Math.random());var g=0;if(relatedTitles.length>1){document.write("<h2 class=’updated’>"+relatedpoststitle+"</h2>")}document.write("<ul>");while(g<relatedTitles.length&&g<20&&g<maxresults){document.write(‘<li><a href="’+relatedUrls[f]+’" title="’+relatedTitles[f]+’">’+relatedTitles[f]+"</a></li>");if(f<relatedTitles.length-1){f++}else{f=0}g++}document.write("</ul>");relatedUrls.splice(0,relatedUrls.length);relatedTitles.splice(0,relatedTitles.length)}/*]]>*/</script>

     Please convert it to the after page load function.