I know that there is a lot of discussion on the defer and async attributes, but I would like to clear up the correct usage in modern browsers.
If I want to include a library file on which the second script depends, I gather that async is no good. To load them in the correct order I need something like:
<script src="library.js" defer></script>
<script src="main.js" defer></script>
From what I read, deferred scripts run automatically before the DOMContentLoaded event is triggered. Does this mean the following is now redundant?
// main.js
document.addEventListner('DOMContentLoaded',init);
function init() {
}
Using the defer attribute, which is avaialable on all modern browsers, can I dispense with waiting to start the script?
Yes, waiting for
DOMContentLoadedin a deferred script is redundant*. There’s really no reason to do it even if you care about compatibility with browsers that don’t support the attribute, because you may as well just removedeferat that point.Related spec information: Window.onload vs script defer
* as with many things, contrived exceptions exist, like when you have a dependency on a later deferred script