Document readystate javascript

document readyState in javascript indicates the various loading stages of a html webpage. Whenever the value of this property changes, a readystatechange event is triggered on the document object.
This event allows you to respond to changes in the document’s state, providing a way to execute code as the page progresses through its loading phases.

document readyState in javascript has different values:

loading :- Document is still in loading states
interactive:- The document has finished loading and parsing, but sub-resources such as scripts, images, stylesheets, and frames may still be loading. This state indicates that the DOMContentLoaded event is imminent.
complete :- The document and all sub-resources have finished loading.

Different states of readiness in javascript

switch (document.readyState) {
  case "loading":
    // document loading.
    break;
  case "interactive": {
    // document finished loading .
    // Assets such as scripts, images, stylesheets and frames are still loading.
    const span = document.createElement("span");
    span.textContent = "A  element.";
    document.body.appendChild(span);
    break;
  }
  case "complete":
    // fully loaded.
    console.log(
      `The first CSS rule is: ${document.styleSheets[0].cssRules[0].cssText}`,
    );
    break;
}

alternative to DOMContentLoaded event

// Alternative to DOMContentLoaded event
document.onreadystatechange = () => {
  if (document.readyState === "interactive") {
    console.log("Document is interactive, but not fully loaded yet.");
  }
};

an alternative to load event:

// Alternative to load event
document.onreadystatechange = () => {
  if (document.readyState === "complete") {
    console.log("Document is fully loaded.");
  }
};

readystatechange as event listener to insert or modify the DOM before DOMContentLoaded

document.addEventListener("readystatechange", (event) => {
  if (event.target.readyState === "interactive") {
    console.log("Document is interactive, but not fully loaded yet.");
  } else if (event.target.readyState === "complete") {
    console.log("Document is fully loaded.");
  }
});