16

Avoid Javascript blocking content download on your website during page load

Posted by php-manual on Mar 18, 2009 in Web

Around 80% of the end-user response time is spent on the front-end. A fair share of this time is spent on downloading components of the page like scripts, Flash, stylesheets, images etc.  Javascript takes majority of the loading time of a webpage because scripts block parallel downloading and rendering in the page. Even if you do not have a lot of Javascript files to load on your webpage they can still block loading other content on your page while they load.  Lets have a look at how the standard javascript file include method and the script DOM element method in detail below.

Standard Javascript file include method


<SCRIPT src="A.JS" language="JavaScript/text"></SCRIPT>
<SCRIPT src="B.JS" language="JavaScript/text"></SCRIPT> 

<IMG src="1.GIF" />
<IMG src="2.GIF" />
<IMG src="3.GIF" />
Javascript blocks the other elements from loading

Javascript blocks the other elements from loading (Example)

Script DOM element method


var p = g.getElementsByTagName("HEAD")[0];
var c = g.createElement("script");
c.type= "text/javascript";
c.onreadystatechange = n;
c.onerror = c.onload = k;
c.src = e;
p.appendChild(C);
Javascript executed without blocking any element from loading

Javascript executed without blocking any element from loading

This method creates a DOM element for each Script and then adds the element to the HTML. 

NOTE

1) Only when the appendChild function is called the Javascript will be executed.
2) For inlined code that depends on the Javascript and also for a similar method of Asynchronous Script Loading - See Steve Souders blog
3) If you go to MSN.com (Alexa top 10 site based on traffic) and hit view source you can see the javacript elements are included by using the script dom element to load the web pages faster. This is a good example of where you can use the script dom element method for certain js files that do not have inlined code dependency. Let us run a Pagetest waterfall report and you can see the following for MSN.COM

Javascript loading in MSN does not block

Pagetest Waterfall report of MSN.COM shows no blocking during page load

Tags: , ,

Copyright © 2010 PHP, Web and IT stuff All rights reserved. PHP Web development in London.