Thursday, July 11, 2013

Fine Tune JavaScript - Defer Script execution

Deferring execution of scripts is one of the techniques used to write non-blocking JavaScript code.  HTML provides the defer attribute for the <script> tag. When present, it specifies that the script is executed when the page has finished parsing/loading.  

Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).

For example this case the script will not run until after the page has loaded:

 

  <script src="demo_defer.js" defer></script>

 

As soon as the <script> tag is parsed, JavaScript file will begin downloading, but the code will not be executed until the DOM has been completely loaded (before the onload event handler is called). It doesn’t block the browser’s other processes, and so these files can be downloaded in parallel with others on the page.

 

 


No comments: