Skip to content

Document onload JavaScript

  • by

The JavaScript onload event is fired when a document or a specific element within it has completed loading. It is often utilized to execute JavaScript code or carry out specific tasks once the entire page content has finished loading.

Here’s the syntax for using the onload event in JavaScript:

Document onload event:

window.onload = function() {
  // Your code here
};

Element onload event:

var element = document.getElementById("elementId");
element.onload = function() {
  // Your code here
};

In both cases, you assign a function to the onload event, which will be executed when the corresponding entity has finished loading.

For the document onload event, the code is attached to the window.onload property. The provided function will execute when the entire document, including its resources, has finished loading.

For an element onload event, you first need to select the desired element using a method such as getElementById, getElementsByClassName, or querySelector. Then, you assign the function to the onload property of the selected element. The function will be executed when that specific element has finished loading.

Document onload JavaScript example

Simple example code that demonstrates the usage of the onload event for the document:

<!DOCTYPE html>
<html>
<head>
  <title>Document onload Example</title>
  <script>
    window.onload = function() {
      // Code to be executed when the document has finished loading
      console.log("Document loaded!");
    };
  </script>
</head>
<body>
  <h1>Document onload Example</h1>
  <p>This is an example demonstrating the document onload event.</p>
</body>
</html>

Output:

Document onload JavaScript

Comment if you have any doubts or suggestions on this JS basic topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *