JS onload event

The onload event in JavaScript is used to execute code when an HTML element has been fully loaded. This event is commonly utilized to run scripts after the page and all its resources (like images, stylesheets, and subframes) have been completely loaded. It is particularly useful for initializing scripts that depend on the full loading of the page's content.

onload Attribute in HTML

In HTML, the onload attribute can be applied to various elements, but it is most commonly used with the <body> tag. This attribute triggers a function when the specified element (e.g., the entire page) finishes loading.

Syntax:

<element onload="functionName()">...</element>

Example:

<body onload="initPage()">
  <h4>Welcome to Way To Code !!</h4>
  <script>
    function initPage() {
      alert("Page has fully loaded!");
    }
  </script>
</body>

window.onload and document.onload

window.onload: This event is triggered when the entire page, including all dependent resources like images, stylesheets, and subframes, has been fully loaded. This is often used for scripts that need to interact with the entire page's content.

Example:

<h1>Welcome to Way To Code</h1>
<script>
    window.onload = function() {
        alert("Entire page, including resources, has loaded!");
    };
</script>

document.onload: This event is not standard in modern JavaScript. Typically, you'd use document.addEventListener('DOMContentLoaded', callback) instead. The DOMContentLoaded event fires when the HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. This is often used for scripts that only need to interact with the HTML content, not the entire page.

Example:

<h1>Welcome to My Website</h1>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        alert("HTML document has been fully loaded and parsed!");
    });
</script>