Lazy loading JavaScript to improve site speed

http://w3bits.com/async-javascript/

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 thesrc 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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值