Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
DOMContentLoaded 
2.1.
Scripts
2.2.
Styles
3.
window.onload
4.
window.onunload
5.
window.onbeforeunload
6.
FAQs
6.1.
What is addEventListener() function?
6.2.
What is an event in JavaScript?
6.3.
Write short notes on readyState.
7.
Conclusion
Last Updated: Mar 27, 2024

JavaScript Page Load

Author Pankhuri Goel
0 upvote

Introduction

There are three significant events in the lifecycle of an HTML page:

  1. DOMContentLoaded: the browser has fully loaded HTML, and the DOM tree has been constructed, but external resources such as images and stylesheets may not have yet loaded.
  2. load: HTML and all external resources such as graphics and styles are loaded.
  3. beforeunload/unload: the user is about to leave the page.

 

Each incident has the potential to be beneficial:

  • DOMContentLoaded event: The handler can find DOM nodes and initialise the interface now that the DOM is ready.
  • load event: External resources are loaded, allowing styles to be applied and picture sizes to be determined, among other things.
  • beforeunload event: The user is about to leave; thus, we can see if they saved their modifications and inquire if they want to go.
  • unload: Although the user has almost left, we can still perform some actions, such as sending out statistics.

 

Let’s look into the specifics of these events.

DOMContentLoaded 

The DOMContentLoaded event happens on the document object. To capture it, we’ll need to use addEventListener.

As demonstrated in the example, when the document is loaded, the DOMContentLoaded handler is called, and it can view all of the elements, including the <img> below.

<script>
  function ready() {
    alert('DOM is ready');

    console.log('Logo has been loaded!!!');
  }

  document.addEventListener("DOMContentLoaded", ready);
</script>

<img id="img" src="logo.png">

It does not, however, wait for the image to load. As a result, the alert displays zero sizes.

The DOMContentLoaded event appears to be pretty straightforward at first glance. The DOM tree is complete – now for the event. Albeit, There are a few quirks.

Scripts

When a browser encounters a <script> tag in an HTML document, it must execute it before proceeding to build the DOM. That’s a precaution, as scripts may wish to edit DOM and even document.write into it. Thus DOMContentLoaded has to wait.

As a result, DOMContentLoaded occurs after such scripts:

<script>
  document.addEventListener("DOMContentLoaded", () => {
    alert("DOM is ready!");
  });
</script>

<script src="demo.js"></script>
  
<script>
    alert("Library is loaded and Inline Script has been executed");
</script>

Styles

DOMContentLoaded does not wait for external style sheets because they do not affect the DOM.

However, there is a glitch. If we have a script after the style, then the script must wait till the stylesheet loads:

<link type="text/css" rel="stylesheet" href="style.css">
<script>
   alert(getComputedStyle(document.body).marginTop);
</script>

This is because, in some cases, such as in the example above, the script may need to obtain coordinates and other style-dependent properties of elements. Thus, it must wait for styles to load.

In the same way that DOMContentLoaded waits for scripts, it now also waits for styles.

window.onload

When the entire page, including styles, pictures, and other resources, is loaded, the load event on the window object is triggered. The onload attribute provides access to this event.

Because window.onload waits for all pictures; the sample below appropriately displays image sizes:

<script>
  window.onload = function() {
    alert('Page is loaded!!!');
        console.log('Logo has been loaded!!!');
      };
</script>
  
<img id="img" src="logo.png">

The load event is also supported by <img> and <script> elements.

window.onunload

The unload event is triggered on the window when a visitor departs the page. Anything we can do there is such that it doesn’t require a delay, such as shutting relevant popup windows.

Sending analytics is a significant exception.

Let’s say we collect information about how the page is utilised, such as mouse clicks, scrolls, and seen page areas.

The unload event occurs when a user leaves our site, and we want to store their data on our server.

The standard https://w3c.github.io/beacon/ describes a particular navigator.sendBeacon(url, data) function for such needs.

The data is sent in the background. The move to another page is seamless: the browser leaves the page but continues to sendBeacon.

Let us see how does it work:

let analyticsData = { /* gathered data in the form of an object */ };

window.onunload = (event) => {
  navigator.sendBeacon("/analytics", JSON.stringify(analyticsData));
});

The browser has probably already exited the document when the sendBeacon request is completed, so there’s no way to retrieve a server response (which is usually empty for analytics).

We won’t be able to cancel the transition to another page here. We can, however, utilise another event called onbeforeunload.

window.onbeforeunload

The beforeunload handler requests extra confirmation if a visitor navigates away from the website or tries to dismiss the window.

If we cancel the event, the visitor’s browser may ask if they are sure.

You can test it out by running the following code and then refreshing the page:

window.onbeforeunload = function() {
  return false;
};

Returning a non-empty string also counts as cancelling the event for historical reasons. Browsers used to display it as a message, but the new specification states that they should not.

The behaviour was altered because some webmasters exploited this event handler by displaying misleading and unpleasant messages. So, for the time being, ancient browsers may still show it as a message, but there is no ability to change the message displayed to the user.

FAQs

What is addEventListener() function?

An event listener is a JavaScript procedure that waits for an event to happen. A user clicking the mouse or pushing a key on the keyboard is a simple example of an event. The addEventListener() is a built-in JavaScript function that takes two arguments: the event to listen for and a second argument that will be called once the described event occurs. A single element can have any number of event handlers without overwriting existing event handlers.

Syntax: element.addEventListener(event, listener, useCapture);

 

What is an event in JavaScript?

An HTML event can be initiated by the browser or the user. The "things" that happen to HTML components are called HTML events. JavaScript can "respond" to these events when it is used on HTML pages.

 

Write short notes on readyState.

The current state of the document is represented by document.readyState, and changes are recorded using the readystatechange event:
→ loading: The document is currently being loaded.
→ interactive: The document is parsed, which co-occurs as the DOMContentLoaded but before it.
→ complete: The document and resources are loaded, which happens before window.onload but around the same time.

Conclusion

In this article, we learned about various page load events in Javascript. We learnt about DOMContentLoaded, load, unload and beforeunload events.

We hope this blog has helped you enhance your knowledge. If you want to learn more, check out our articles on JAVASCRIPT DOM STYLING - Coding Ninjas Coding Ninjas StudioJavascript DOM navigation - Coding Ninjas Coding Ninjas Studio and DOM Manipulation in Javascript - Coding Ninjas Coding Ninjas Studio. Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practice top problems, follow guided paths, attempt mock tests, read interview experiencesinterview bundle, solve problems, participate in contests and much more!

Happy Reading!

Live masterclass