Explain load events in JavaScript?


The page load events in JavaScript are fired when the page loads or unloads. Following are the events −

EventDescription
DOMContentLoadedThis is fired when the dom tree has been built but external resources like stylesheets ,images, etc are still not loaded.
LoadIt is fired when the browser fully loads all the resources.
BeforeunloadIt is fired before the page and resources are being unloaded and can be used to confirm if the user really wants to leave.
UnloadIt is fired when the page is fully unloaded.

Following is the code for load events in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      color: blueviolet;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Load events in Javascript</h1>
<div class="result"></div>
<script>
   let resEle = document.querySelector(".result");
   document.addEventListener("DOMContentLoaded", () => {
      resEle.innerHTML = "The DOMContentLoaded event has fired <br>";
   });
</script>
</body>
</html>

Output

Updated on: 16-Jul-2020

591 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements