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.

Related posts:

  1. Improve Readability of Web pages
  2. See hidden Facebook photo albums…
,
  • 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.

  • 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://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://twitter.com/shimmyohana shimmy ohana

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

  • http://www.onlythebible.com Eman

    Love your search feature!
    Great site.

  • 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://www.sareez.com/ sarees

    great…

  • 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!

  • Prakash

    got it man………..

  • http://www.tutkiun.com/2010/08/sleep-mode-for-websites.html Sleep mode for websites | Tutkiun!

    [...] will increase loading time of your pages a little which can be off course optimized by loading JavaScript code after page load. Putting this code just before tag will also ensure the content on your site gets loaded first. If [...]

  • Anonymous

    ok

blog comments powered by Disqus