Lazy loading JavaScript to improve site speed

A 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 media assets, we can see JavaScript everywhere.

JavaScript lowers down the resource consumption at the server by performing a lot of tasks at the client-side. But from a different perspective, it slows down the web as well.

Async JavaScript

Its 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 blocks other resources like markup, media etc. from downloading into the web browser.

To avoid such blocks, the small blocks of JavaScript should be written inline in the markup, and the big blocks should be kept in separate files that should be loaded asynchronously.

Lazy loading or Asynchronous JavaScript

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.

HTML5 async

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>

JavaScript to load .js files async

The async 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 code 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);
}

Load multiple JavaScript files asynchronously

The above two code 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>

That’s it. Feel free to post your thoughts on this and share the methods you use to lazy-load JS.