As you know, you can work with DOM on the document element's DOMContentLoaded event, without waiting for the window.onload event. But there is also the document.onreadystatechange event, which, when first generated, indicates that the DOM structure is ready (document.readyState with this == interactive). document.readyState == interactive we get a bit before the DOMContentLoaded event, the question is why? What exactly hasn't been loaded between the first generation of document.onreadystatechange and the DOMContentLoaded event? The screen shows the time from the beginning of the page loading and the event.
1 answer
A very interesting question. I became interested and a bit deep into the topic. Perhaps I found the right answer. Later I will definitely conduct "experiments" for confirmation, but for now preliminary data)
Here on this page is a detailed (as opposed to dry and formal off-line documentation) description of the principle of how the DOMContentLoaded
event DOMContentLoaded
. If you look at it in detail, you will notice that the event, nevertheless, is waiting for some styles to be loaded, for example, in case they block execution inside <script>
on the page.
Apparently, this distinguishes DOMContentLoaded
from Document.readyState == interactive
, which, apparently, is called immediately after the parsing of the page.
These conclusions are supported by the answer to this similar question:
https://stackoverflow.com/questions/3665561/document-readystate-of-interactive-vs-ondomcontentloaded
Briefly translation of the answer:
After the document is parsed, the browser performs the following steps:
Sets the document readiness status to " interactive ".
Removes all nodes (nodes) from the stack of open items.
(most interesting) If the list of scripts that will be executed after the document has been parsed is not empty, it performs the following actions: it waits for the first script to be ready for execution and that there are no style sheets blocking it, then it does; expects readiness for the execution of the second of the scripts and the absence ... and so on until all the scripts that have been waiting for execution after the parsing of the document have been executed.
Places a simple DOMContentLoaded bubble event in the call queue .
- Apparently it is, DOMContentLoaded also waits for the loading of scripts, but onreadystatechange is not. So it’s safer to work with DOM on the DOMContentLoaded event, as there may be some kind of preliminary manipulation in the loaded scripts. - Kot