Asynchronous, Lazy loading of JavaScript to improve site speed

A handy guide to load external JavaScript files asynchronously – covering JavaScript, jQuery and HTML5 solutions to lazy load scripts and speed up website.

The use of JavaScript is so common on web. Ranging from site functionality, visitor tracking, advertisement to social share buttons, we can see JavaScript everywhere. But from a different perspective, it slows down the web as well.

It’s not that only JavaScript files are responsible to slow down a website, but a number of other factors too. What I mean by above is that unnecessary use of JavaScript should be avoided, and if used, it should not affect the load time of a webpage.

How does JavaScript increase page load time?

A web browser renders a webpage by reading it’s markup (HTML). If the markup contains an external JavaScript file, the browser stops loading the markup and starts downloading that external JavaScript – this causes a block in webpage rendering (known as render blocking or parser blocking). The process continues to repeat on every next JavaScript file on a webpage, and therefore, it slows down the page to a greater degree.

The render block also causes Resource blocking, when the external JavaScript files while loading stops other resources like markup, media etc. from downloading into the web browser.

Fast loading websites are always good for both: the user and the search engine. And asynchronous loading of JavaScript is one step closer to a faster web. Note that asynchronous loading and lazy loading have same meaning with reference to JavaScript.

How does async JavaScript improve website load time?

Asynchronous JavaScript avoids the direct calling of .js files in the markup. The scripts are loaded by JavaScript functions by dynamically creating the <script> element, and supplying it the src and other attributes.

Generally, .js files are called in the markup using the following syntax:

<script src="http://example.com/script.js"></script>

The easiest way to call our script asynchronously is the HTML5 async attribute that prevents render blocking with external JavaScript files. So, below is how we rewrite the above syntax with the async attribute:

<script async src="http://example.com/script.js"></script>

The attribute works fine on modern browsers – supported by Firefox 3.6+, IE 10+, Chrome 2+, Safari 5+, iOS 5+, Android 3+. However, for a deeper browser support, I will recommend a different way of doing it:

<script>
  var resource = document.createElement('script'); 
  resource.async = "true";
  resource.src = "http://example.com/script.js";
  var script = document.getElementsByTagName('script')[0];
  script.parentNode.insertBefore(resource, script);
</script>

The above script works on every browser, hence avoiding the fear of cross-browser incompatibility issues.

Here is a more better, neater, efficient version of the above async JavaScript snippet:

window.onload = function() {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'http://yourdomain.com/script.js';
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
}

Function to load multiple JavaScript files asynchronously

The above two snippets to load JavaScript dynamically involves using the same block of code again-and-again, replacing the src attribute value to your target JS file. The below code snippet will save you a lot of lines of code to achieve the same thing:

<script type="text/javascript">
function script(url) {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = url;
    var x = document.getElementsByTagName('head')[0];
    x.appendChild(s);
}
</script>

Now, with the above function, you just need to write a single line to load a JavaScript file:

<script>script('http://yoursite.com/your-script.js');</script>

Similarly, to load multiple JavaScript files, you will write:

<script>
script('http://yoursite.com/your-script.js');
script('http://yoursite.com/my-script.js');
script('http://yoursite.com/third-party-script.js');
</script>

Lazy loading scripts with jQuery

If you utilize jQuery library on your website, this snippet will let you accomplish async loading of external JS files:

<script>
$.ajax({
  url: 'http://yoursite.com/script.js',
  dataType: 'script',
  cache: true, // or get new, fresh copy on every page load
  success: function() {
    // Callback
  }
}</script>

More Resources