Javascript: Increasing performance using Dynamic Loading

Javascript: Increasing performance using Dynamic Loading
4.71 (94.29%) 7 votes

  6 minutes

 

Hello folks,

So we are back again with a new article regarding Javascript. This time we will talk about increasing the performance of web pages by different methods. So lets start with a fact.

Earlier while rendering HTML when browser finds script tag it stops everything else and load the script and execute it first then only proceed.

This was the fact now lets talk about it further.

 

Script Positioning

HTML 4 specifies that script may be present in <head> or <body> tag in html and can comes any number of times. Traditionally <script> tags are know for leading external JS and <link> tags for loading CSS.

The theory was that it’s best to load them first so that the page will come in looking and behaving correctly.

For Example

<html>
  <head>
    <script type="text/javascript" src="a.js"></script>
    <script type="text/javascript" src="b.js"></script>
    <script type="text/javascript" src="c.js"></script>
    <link rel="stylesheet" type="text/css" href="d.css">
  </head>
  <body>
   Hello world
  </body>
</html>

Since each <script> tag blocks the page from continuing to render until it has fully downloaded and executed the JavaScript code, the perceived performance of this page will suffer. Let me mention one more thing.

Browser doesn’t start rendering anything until it finds the body tag. 

Since <script> is in <head> tag. It makes the page unresponsive until the all the JS files are loaded and executed. Which in turn increases the first response time which is very important in terms or UX.

Browsers after Internet Explorer 8, Firefox 3.5, Safari 4, and Chrome 2 all allow parallel downloads of JavaScript files. This is a good news because <script> tag will now not stop other <script> tags from downloading external resources.

Unfortunately <script> tags stop other resources like images and css to download. This is again a holdback for the solution that browsers provided by providing parallel downloads. Script blocking still remains a problem.

For solving this, simply we have to load the Script resources as late as possible or say closest to the bottom. With this <script> tag will be encountered at last and everything else will be loaded already and now we can load external script resources in parallel.

 

<html>
 <head>
    <link rel="stylesheet" type="text/css" href="d.css">
    <link rel="stylesheet" type="text/css" href="t.css">
 </head>
 <body>
   Hello world
   <script type="text/javascript" src="a.js"></script>
   <script type="text/javascript" src="b.js"></script>
   <script type="text/javascript" src="c.js"></script>
 </body>
</html>

This is the recommended position to put the script tag so that <link> tag resources will be loaded in parallel and then <script> resources are loaded in parallel.

 

Combining Scripts

As we know now that every time <script> tag is encountered, everything will stop and download of script resource and its execution will happen. So keeping less number of Script tag saves the time as it has less download time. In this case downloading 4 small files(1kb) will take more time than downloading 1 big (4kb), off-course the size is same of small one and the big one.

Thus you can improve the performance of website by concatenating many script resources in one and thus save the download time and execution by using simple <script> tag.

Yahoo! created the combo handler for use in distributing the Yahoo! User Interface (YUI) library files through their Content Delivery Network (CDN). Any website can pull in any number of YUI files by using a combo-handled URL and specifying the files to include. For example, this URL includes two files: http://yui.yahooapis.com/combo ?2.7.0/build/yahoo/yahoo-min.js&2.7.0/build/event/event-min.js.

 

Non Blocking Scripts

Javascript blocks all the Http calls and other resources calls and thus cause the performance a big threat. To make the Javascript Non blocking we can avoid loading it at start and load it after everything else is loaded. We should load the scripts after windows.onload event is fired.

 

Deferred Scripts

HTML4 has an attribute called defer. Though it is not supported by all the browsers. What it does is it indicates that the script contained within the element is not going to modify the DOM and therefore execution can be safely deferred until a later point in time. If you are working with Internet Explorer 4+ and Firefox 3.5+ you can make use of this attribute. Use it like this

<script type="text/javascript" src="a.js" defer></script>

 

Dynamic Script Element

The Document Object Model (DOM) allows you to dynamically create almost any part of an HTML document using JavaScript. Thus we can also generate script element and hence make it load at later stage thus saving the parallel loading of other elements. How we do this is below.

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'file.js';
document.getElementsByTagName('head')[0].appendChild(script);


The file begins downloading as soon as the element is added to the page. The important thing about this technique is that the file is downloaded and executed without blocking other page processes, regardless of where the download is initiated.

 

XMLHTTPREQUEST script injection

Through this we request for the given file and load it first and then add it to the element.

var xhr= new XMLHttpRequest();
xhr.open("get","file.js",true);
xhr.onreadystatechange = function(){ 
  if (xhr.readyState == 4){
    if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
      var script = document.createElement("script"); 
      script.type = "text/javascript"; 
      script.text = xhr.responseText; 
      document.body.appendChild(script); 
    } 
  }
}; 
xhr.send(null);

The primary limitation of this approach is that the JavaScript file must be located on the same domain as the page requesting it, which makes downloading from CDNs impossible.

 

Conclusion

We must always try to load JS at the end as it will not hinder the loading of other resources and made the page more responsive. Minimize the script tags and write them where they require of do the dynamic loading. Its all up to you how you tame the monster.

So these were the few methods through which you can increase the performance of your website by making the javascript non blocking and load in parallel. We will talk more about Javascript and browsers in following articles. Don’t forget to subscribe to get updates on latest tech news.

The article is derived from the book High Performing Javascript By Nicholas C. Zakas

Also Read

https://www.learnsteps.com/javascript-increase-performance-by-handling-dom-with-care/

https://www.learnsteps.com/javascript-increasing-performance-by-handling-scopes-smartly/

https://www.learnsteps.com/javascript-difference-between-strict-and-lenient-equality/

https://www.learnsteps.com/javascript-confusing-concepts-and-uncertainities/

For more such articles subscribe

 


Gaurav Yadav

Gaurav is a Full Stack Web Developer and Blogger. Sportsperson by heart and loves football. He has experience with various frameworks in php, python and javascript. Loves to explore new frameworks and evolve with the trending technology.

Leave a Reply

Your email address will not be published. Required fields are marked *