This technique tries to defer JavaScript file download and execution until page loaded. Some experienced web developers use this technique to improve the rendering speed of a site.
Can it really make your website load faster?
Short answer: Yes. Like style sheets, scripts must be downloaded, parsed, and executed before the browser can begin to render a web page. Again, even if a script is contained in an external file that is cached, processing of all elements below the script is blocked until the browser loads the code from disk and executes it. However, for some browsers, the situation is worse than for stylesheets: while JavaScript is being processed, the browser blocks all other resources from being downloaded. For AJAX-type applications that use many bytes of JavaScript code, this can add considerable latency.
Should we defer loading of all external JavaScript?
It depends on your scripts. Some scripts that are not actually used by the document before the onload event can be deferred, like a bulk of JavaScript code that handles user-initiated events, such as mouse-clicking and dragging, form entry and submission, hidden elements expansion, and so on. All of these user-triggered events occur after the page is loaded and the onload event is triggered.
The JavaScript Code
We can use the following JavaScript function to defer the loading of an external script.
function deferLoadingScript(url, callback) { var loadScript = function() { var s = document.createElement('script'); s.type = 'text/javascript'; s.src = url; if (typeof callback === 'function') { s.onload = s.onreadystatechange = function(event) { event = event || window.event; if (event.type === 'load' || (/loaded|complete/.test(s.readyState))) { s.onload = s.onreadystatechange = null; callback(); } }; } document.body.appendChild(s); }; if (window.addEventListener) { window.addEventListener('load', loadScript, false); } else { window.attachEvent('onload', loadScript); } }
Usage example of the function is shown below.
/* Defer loading of a script */ deferLoadingScript('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js'); /* Defer loading of a script with callback function */ deferLoadingScript('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js', function() { console.log('Done loading bootstrap.min.js'); });
Hi Jose,
Doesn't the HTML "defer" do just the same?
e.g.
as seen at: https://www.w3schools.com/tags/att_script_defer.asp
Hi Tedy, there are some differences. The JavaScript function above defers both the download and execution of a script and the script is executed on window's load event, whereas the
defer
attribute only defer the execution and the script is executed before DOMContentLoaded event. So it depends on your needs.Where should I put the function? head, body, /body?
Thanks
Hi Jose, you can put the script at the bottom of your web page right before the closing </body> tag.