Downloading javascript Without Blocking

Posted by doug on Stack Overflow See other posts from Stack Overflow or by doug
Published on 2010-04-18T09:37:17Z Indexed on 2010/04/18 9:43 UTC
Read the original article Hit count: 278

Filed under:
|
|
|

The context: My question relates to improving web-page loading performance, and in particular the effect that javascript has on page-loading (resources/elements below the script are blocked from downloading/rendering).

This problem is usually avoided/mitigated by placing the scripts at the bottom (eg, just before the tag).

The code i am looking at is for web analytics. Placing it at the bottom reduces its accuracy; and because this script has no effect on the page's content, ie, it's not re-writing any part of the page--i want to move it inside the head. Just how to do that without ruining page-loading performance is the crux.

From my research, i've found six techniques (w/ support among all or most of the major browsers) for downloading scripts so that they don't block down-page content from loading/rendering:

(i) XHR + eval();

(ii) XHR + 'inject';

(iii) download the HTML-wrapped script as in iFrame;

(iv) setting the script tag's 'async' flag to 'TRUE' (HTML 5 only);

(v) setting the script tag's 'defer' attribute; and

(vi) 'Script DOM Element'.

It's the last of these i don't understand. The javascript to implement the pattern (vi) is:

(function() {
  var q1 = document.createElement('script');
  q1.src = 'http://www.my_site.com/q1.js'
  document.documentElement.firstChild.appendChild(q1)
})();

Seems simple enough: inside this anonymous function, a script element is created, its 'src' element is set to it's location, then the script element is added to the DOM.

But while each line is clear, it's still not clear to me how exactly this pattern allows script loading without blocking down-page elements/resources from rendering/loading?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html