Friday, 3 March 2017

javascript - Where should I put tags in HTML markup?

Here's what happens when a browser loads a website with a


Welcome back, user





Javascript:




// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});


Because your browser does not know my-script.js isn't going to modify the document until it has been downloaded & executed, the parser stops parsing.



Antiquated recommendation




The old approach to solving this problem was to put



Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible to script 2 is downloaded & executed before script 1.



According to http://caniuse.com/#feat=script-async, 94.57% of all browsers support this.




defer







Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.



Unlike async scripts, defer scripts are only executed after the entire document has been loaded.




According to http://caniuse.com/#feat=script-defer, 94.59% of all browsers support this. 94.92% support it at least partially.



An important note on browser compatibility: in some circumstances IE <= 9 may execute deferred scripts out of order. If you need to support those browsers, please read this first!





The current state-of-the-art is to put scripts in the tag and use the async or defer attributes. This allows your scripts to be downloaded asap without blocking your browser.



The good thing is that your website should still load correctly on the 6% of browsers that do not support these attributes while speeding up the other 94%.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...