Account
Categories

JavaScript onload Event: Page Load


Definition

When you use the onload event on a webpage, it runs only after the whole page is fully loaded, including all text and images.

It can also show a message to the user that the page has loaded successfully. It is called the online event.

Now you will clearly understand with the help of the flowchart.

Start
   |
   v
User opens the webpage
   |
   v
The browser loads all text, images, and files
   |
   v
Is the whole page loaded?
   |
   |-- No --> Keep loading the page
   |
   |-- Yes --> Run onload event
                |
                v
            Show message: "Page loaded successfully."
   |
   v
End
  

Syntax:

<body onload="myFunction()">

Example:

<!DOCTYPE html>
<html>
<body onload="showMessage()">

<h2>Onload Event Example</h2>

<script>
// This function runs only when the whole page is fully loaded.
function showMessage() {
  alert("Page loaded successfully!");
}
</script>

</body>
</html>
Output:
When the webpage finishes loading completely, a popup alert appears with the message:
"Page loaded successfully!"