I thought I knew how to use 'defer' attribute when referencing external scripts from my html pages. I even thought there is no reason for me NOT to use it. But after a couple of unexpected things i started to research (even here) and I think I'm not 100% sure when it's safe to use it every time I use the script tag.
Is there somewhere a list of known use cases when defer should NOT be used?
The only thing defer
does is run your script when the DOM has finished parsing, but before the DOMContentReady
event is fired off.
So: if your code does not depend on the DOM (directly, or indirectly through access to document
properties that can only be determined once the DOM is done), there is no reason to defer
. For example: a utility library that adds a new namespace ComplexNumbers
, with a ComplexNumber
object type and associated utility functions for performing complex number maths, has no reason to wait for a DOM: it doesn't need to be deferred. Same for a custom websocket library: even if your own use of that library requires performing DOM updates, it does not depend on the DOM and doesn't need defer
.
But for any code that tries to access anything related to the DOM: you need to use defer
. And yes: you should pretty much have defer
on any script that loads as part of the initial page load, and if you did your job right, none of those scripts interfere with each other when they try to touch the various pieces of the DOM they need to work with.
In fact, you should have both defer
*and* async
, so as not to block the page thread. The exception being if you're loading a type="module"
script, in which case you don't get a choice in deferral: it's deferred by default. but it'll still need async
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.