0

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?

Manngo
  • 14,066
  • 10
  • 88
  • 110
  • based on [docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer) yes - is there a reason you think this isn't doing what you need? though you may want to read the notes in the browser compatibility table at the end of that doc if you're using Chrome, and the document is loaded as XHTML – Bravo Aug 21 '21 at 02:14
  • @Bravo No, I’m not having any problems. I wanted clarification for teaching purposes. I have always used the older techniques for deferring my scripts, but I want to make sure that I understand the newer `defer` attribute correctly. – Manngo Aug 21 '21 at 02:17

1 Answers1

0

Yes, waiting for DOMContentLoaded in 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 remove defer at 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

Ry-
  • 218,210
  • 55
  • 464
  • 476