feklee
feklee

Reputation: 7695

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.

Upvotes: 19

Views: 21163

Answers (3)

Moba
Moba

Reputation: 159

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', ...

Upvotes: 5

Markus
Markus

Reputation: 700

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.

Upvotes: 1

user1726343
user1726343

Reputation:

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.

Upvotes: 12

Related Questions