Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.readyState on DOMContentLoaded?

In browsers that support the event DOMContentLoaded and the property document.readyState:

When DOMContentLoaded fires, can I assume that the value of document.readyState will always be either "complete" or "interactive"/"loaded"?

(Or could it be that document.readyState sometimes still has the value "loading"?)

In your answer please provide a reference to an authoritative source.

You may wonder: Why not just listen to readystatechange? It is because the Android 2.3.5 standard browser is a target platform, and it does not implement the readystatechange event.

like image 453
feklee Avatar asked Nov 12 '12 15:11

feklee


3 Answers

The value of the readyState property is always "interactive" when DOMContentLoaded has fired. This is evidenced by the fact that the MDN documentation claims:

// alternative to DOMContentLoaded event
document.onreadystatechange = function () {
  if (document.readyState == "interactive") {
    initApplication();
  }
}

is interchangeable with a DOMContentLoaded handler. You can also have a look at the spec here, which reiterates this.

like image 64
Asad Saeeduddin Avatar answered Oct 22 '22 20:10

Asad Saeeduddin


As per accepted answer:

The value of the readyState property is always "interactive" when DOMContentLoaded has fired.

Wrong

It has either of:

  • interactive
  • complete

document . readyState ref.

Returns "loading" while the Document is loading, "interactive" once it is finished parsing but still loading subresources, and "complete" once it has loaded.

If one attach an event listener to readystatechange before Document has state interactive one can check for interactive alone, like with example from MDN. Then one will catch the state if it ever reaches it.

However if one check the state at a later stage it is not.

Also by example from MDN, these are equal:

document.onreadystatechange = function () {
  if (document.readyState === 'interactive') {
    initApplication();
  }
}


document.addEventListener("DOMContentLoaded", function () {
    initApplication();
});

That does not mean:

if (document.readyState !== 'loading')
    assert(document.readyState === 'interactive')

Which the answer suggests.

As to say:

  • document.addEventListener("DOMContentLoaded", ...

will never equal to:

  • window.addEventListener('load', ...
like image 27
Moba Avatar answered Oct 22 '22 21:10

Moba


The value of the readyState property is at least "interactive" when DOMContentLoaded is fired. As @MTCoster pointed out here, the event is deferred until linked scripts with defer attribute and module scripts, linked or inline, have executed. See also this post.

like image 1
Markus Avatar answered Oct 22 '22 22:10

Markus