Lazy loading JavaScript to improve site speed
2015-06-06 01:31
609 查看
http://w3bits.com/async-javascript/
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.
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.
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.
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.
Asynchronous JavaScript avoids the direct calling of
in the markup. The scripts are loaded by JavaScript functions by dynamically creating the <script> element, and supplying it the
other attributes.
Generally,
in the markup using the following syntax:
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
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:
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:
The above two code snippets to load JavaScript dynamically involves using the same block of code again-and-again, replacing the
value to your target JS file. The below code snippet will save you a lot of lines of code to achieve the same thing:
Now, with the above function, you just need to write a single line to load a JavaScript file:
Similarly, to load multiple JavaScript files, you will write:
If you utilize jQuery library on your website, this snippet will let you accomplish async loading of external JS files:
That’s it. Feel free to post your thoughts on this and share the methods you use to lazy-load JS.
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 isso 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.
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 renderblocking 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 asynchronousloading 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 .jsfiles
in the markup. The scripts are loaded by JavaScript functions by dynamically creating the <script> element, and supplying it the
srcand
other attributes.
HTML5 async
Generally, .jsfiles 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
asyncattribute:
<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 srcattribute
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.
相关文章推荐
- javascript在chrome浏览器中无法刷新的问题
- JavaScript中使用concat()方法拼接字符串的教程
- JavaScript中的lastIndexOf()方法使用详解
- JavaScript中操作字符串之localeCompare()方法的使用
- JavaScript中String.match()方法的使用详解
- JavaScript中的replace()方法使用详解
- 简介JavaScript中search()方法的使用
- JavaScript中的slice()方法使用详解
- JavaScript中的substr()方法使用详解
- 简介JavaScript中substring()方法的使用
- JavaScript中的toLocaleLowerCase()方法使用详解
- 简介JavaScript中toUpperCase()方法的使用
- JS多维数组转一维
- Javascript表达式中连续的 && 和 || 之赋值区别
- 函数传参和实际应用—JS学习笔记2015-6-5(第49天)
- 【js】解压缩的问题
- JavaScript Style Attributes
- 事件冒泡与事件捕获
- Javascript 多浏览器兼容性问题
- js 变量类型、相互转换