Search code examples
javascriptdomdeferred-execution

Why are you not supposed to modify the DOM with deferred scripts?


I'm brushing up on my javascript basics, and the book I'm reading stated the following (paraphrased):

"Adding the defer attribute the script element is a promise to the browser that your script will not be making any changes to the DOM"

I was curious as to why this is so? Since deferred scripts aren't executed until after rendering is complete, I would assume that it is safe to modify the DOM in your script.


Solution

  • This is a confusion of terminology about what "the DOM" means. Consulting the HTML4 spec on defer gives us a hint about what's really going on:

    When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering.

    So, what your book means by

    your script will not be making changes to the DOM

    is really

    your script will not be making changes to the document text being parsed

    Your paraphrased quote uses the phrase "the DOM" to refer to the HTML document text being parsed, instead of the JavaScript-accessible object model being created by that parsing. There is no reason why your defered script could not alter the DOM structure (i.e., the one in document) after being parsed, but it certainly cannot alter the document text being parsed, since the document has already been fully parsed when the script runs.