Wednesday, November 7, 2012

Asynchronous JS loading without blocking onload

Asynchronous JS is best way to load js file in your HTML page but it still blocks window.onload event (except in IE before version 10).

checkout here how onload blocked even we use asyn js loading techniques

So here is another solution for same :-)
  1. create an iframe without setting src to a new URL. This fires onload of the iframe immediately and the whole thing is completely out of the way
  1. style the iframe to make it invisible
  1. get the last script tag so far, which is the snippet itself. This is in order to glue the iframe to the snippet that includes it.
  1. insert the iframe into the page
  1. get a handle to the document object of the iframe
  1. write some HTML into that iframe document
  1. this HTML includes the desired script

var iframe = document.createElement('iframe');
(iframe.frameElement || iframe).style.cssText = "width: 0; height: 0; border: 0";
var where = document.getElementsByTagName('script');
where = where[where.length - 1];
where.parentNode.insertBefore(iframe, where);
var doc = iframe.contentWindow.document;'<body onload="'+
'var js = document.createElement(\'script\');'+
'js.src = \''+ url +'\';'+


1. Avoid SSL warnings: iframe.src defaults to “about:blank” in IE6, which it then treats as insecure content on HTTPS pages. We found that initializing iframe.src to “javascript:false”.

2. Avoid crossdomain exceptions: anonymous iframe access will throw exceptions if the host page changed the document.domain value in IE. The original Meebo code falls back to a “javascript:” URL when this happens.

3. The script (asyncjs1.php) runs is in an iframe, so all document and window references point to the iframe, not the host page.There's an easy solution for that without changing the whole script. Just wrap it in an immediate function and pass the document object the script expects:

document.getElementById('r')... // all fine

4. The script works fine in Opera, but blocks onload. Opera is weird here. Even regular async scripts block DOMContentLoaded which is a shame.

seems below code solves our problem ..  try it and let me know the results ...


  1. Hi! I'm at work surfing around your blog from my new iphone 4! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the superb work!

    Feel free to surf to my blog Personal Site
    my website ::

  2. Ӏ could not refrain from commenting. Well wrіtten!

    Here is my web page;
    my website :: HTTP://

  3. I visit everyday some sites and blogs to read posts, but this web
    site provides quality based articles.

    My web blog diet plan for women

  4. Actually when someone doesn't understand afterward its up to other people that they will assist, so here it happens.

    My blog post: flying airplane games