Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today we’ll look at events related to page loading, including DOMContentLoaded, Load, beforeUnload, and unload.

Introduction to the

When we open a page, the following events occur in sequence:

  • DOMContentLoaded– The browser fully loads the HTML and builds the DOM tree. But external resources such as external styles and images are not loaded. At this point we can find the DOM node or initialize the page and so on.
  • load– The browser is fully loaded with HTML as well as external resources such as images and styles.

When we leave a page, the following events occur in sequence:

  • beforeunload– Fires before the page is closed. We can use this event to display a confirmation dialog to prevent the user from accidentally leaving the page. When we fill out a lot of forms, we can prevent the loss of data if we accidentally click on a link to jump to another page.
  • unload– Triggered when the page is closed. You can use this event to send analysis data or do some cleanup.

example

To handle page events, call the addEventListener() method on the Document object:

document.addEventListener('DOMContentLoaded'.() = > {
  // Handle DOMContentLoaded
});

document.addEventListener('load'.() = > {
  // Handle the load event
});

document.addEventListener('beforeunload'.() = > {
  // Handles beforeUnload events
});

document.addEventListener('unload'.() = > {
  // Handles unload events
});
Copy the code

The following example fully illustrates how to handle a page load event:

<! DOCTYPEhtml>
<html>
<head>
  <title>JS page loading event</title>
</head>

<body>
  <script>
    addEventListener('DOMContentLoaded'.(event) = > {
      console.log('DOM load completed.');
    });

    addEventListener('load'.(event) = > {
      console.log('Page load completed.');
    });

    addEventListener('beforeunload'.(event) = > {
      // Displays a confirmation dialog box
      event.preventDefault();
      // Google Chrome needs to set returnValue.
      event.returnValue = ' ';
    });

    addEventListener('unload'.(event) = > {
      console.log('Send statistics');
    });
  </script>
</body>
</html>
Copy the code

You can see this when the first page loads

A confirmation dialog is displayed when TAB is closed. When TAB is closed, an Unload event is triggered to report the data to be counted

conclusion

Today we cover the events related to page loading, DOMContentLoaded, load, beforeUnload, and unload.

Tomorrow we’ll go on to study it in detail.

Learn more front-end knowledge together, wechat search [Xiaoshuai’s programming notes], updated every day