Understand browser readyState and how to track the interactivity of the content on your web page

Learn how to handle the browser events and the state of the document for loading, interactive, and complete

Different readyState of a document

The current state of the document can be accessed using readyState property of the document object. document.readyState tells us the status of the page load.

There are 3 different possible states:

  • loading — The document is loading (the .html file is being downloaded/parsed)
  • interactive — In this state, the DOM is loaded and accessible. However, resources like images, stylesheets, and JavaScript files have not finished downloading/loading/parsing.
  • complete — the document and all resources like images/stylesheets have finished loading.

Let’s look at an example. We have a website gitconnected.com, let’s compare the readyState when we type the URL in the browser and hit enter.

1. Loading

Download the index.html file (this is the default if nothing is specified) from the server and parse it. If you have included any script tags, then those are also downloaded, parsed, and executed.


Once the HTML file is loaded, the readyState changes to interactive, and we can detect this using the readystatechange event.

2.Interactive

In the interactive state the additional files like css/image files are downloaded. Once the readyState status is interactive, this means DOM is loaded, but the resources are downloading. The DOMContentLoaded event is also fired when the readyState changes from loading to interactive.

interactive state

Once all the files are downloaded and parsed, the document readystate will change to complete. In this state, all the resources of the page will be available.

3. Complete

When readyState is changed to complete, it means that the document is now parsed and loaded and all known additional resources like CSS, images, and JS have also been parsed and loaded.

readyStateChange event

To detect the state change, we can add the readyStateChange event listener to the document.

document.addEventListener('readystatechange', function(ev) {
console.log(document.readyState)
});

A complete example of the above states:

https://gist.github.com/Jagathishrex/bb0474097eb95671f491d8c3ea82ce57

Reference: MDN

Follow Javascript Jeep🚙💨.

Leave a comment

Design a site like this with WordPress.com
Get started