JavaScript Lazy loading / Asynchronous loading
10 Nov 2014Where should the JavaScript be placed in a HTML page for optimal performance of a Website ?
JavaScript is inserted in the <script>
tag, which can be put in the <head>
or <body>
sections of HTML.
Placing the <script>
tag at the bottom of <body>
improves the site speed and page load.
Here is the workflow when the Browser loads a Website,
To solve the problem of parallel downloads at the parsing stage, put the <script>
tags at the bottom of the <body>
so that the parser is not blocked till the end.
Another approach is to give HTML5 attributes async
or defer
on the scripts. This way the script tag can be put in the <head>
section of HTML.
Async:
<script type="text/javascript" src="script.js" async></script>
Scripts are executed asynchronously. They are downloaded and executed without blocking the browser, preventing parser blocking and resource blocking.
But the async
attribute is supported by modern browsers only like Chrome2+, Safari 5+, IE 10+ Firefox 3.6+.
To ensure Browser compatibility, we could use the below snippet which works on every browser.
<script>
var resource = document.createElement('script');
resource.async = "true";
resource.src = "js/myScript.js";
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(resource, script);
</script>
Defer:
<script type="text/javascript" src="script.js" defer></script>
Scripts are downloaded and executed after the complete HTML document is parsed.