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?

2
  • based on docs 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 Commented Aug 21, 2021 at 2: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. Commented Aug 21, 2021 at 2:17

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.