The page load events in JavaScript are fired when the page loads or unloads. Following are the events −
| Event | Description |
|---|---|
| DOMContentLoaded | This is fired when the dom tree has been built but external resources like stylesheets ,images, etc are still not loaded. |
| Load | It is fired when the browser fully loads all the resources. |
| Beforeunload | It is fired before the page and resources are being unloaded and can be used to confirm if the user really wants to leave. |
| Unload | It is fired when the page is fully unloaded. |
Following is the code for load events in JavaScript −
Example
<!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
