`questioning the unusual behavior of document.onload(), seeking answers`

Before delving into this, let's avoid downvoting as this is not another typical question about window.onload vs document.onload.

window.onload triggers once all DOM nodes are fully loaded, while document.onload triggers when all DOM nodes are ready without waiting for assets to fully load.

If we use window.onload in the following example:

<!DOCTYPE html>
<html>
    <head>
        <title>Testing out document.onload and window.onload</title>
        <script>
            window.onload = function() {
                alert('Loaded!');
            };
        </script>
    </head>
    <body>
        <img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
    </body>
</html>

The script will wait for the image to be fully loaded before triggering the alert.

On the other hand, if we use document.onload:

<!DOCTYPE html>
<html>
    <head>
        <title>Testing out document.onload and window.onload</title>
        <script>
            document.onload = function() {
                alert('Loaded!');
            };
        </script>
    </head>
    <body>
        <img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
    </body>
</html>

In this case, nothing will happen unless we make our function self-executing like so:

<!DOCTYPE html>
<html>
    <head>
        <title>Testing out document.onload and window.onload</title>
        <script>
            document.onload = function() {
                alert('Loaded!');
            }();
        </script>
    </head>
    <body>
        <img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
    </body>
</html>

Now, the script will work but won't wait for the image to fully load like it does with window.onload.

I have a couple of questions:

  1. Why do we need to create self-executing functions with document.onload, while window.onload works without making our function self-executing? It behaves the same in the latest versions of Chrome and Firefox, so I assume that's how it's intended to work, but why?

  2. What exactly is happening when we assign a function to document.onload? It seems to be a way to await the loading of the DOM. But when we say window.onload = function() { }, are we essentially turning a window into a function? Or does the window have an event listener attached to it that is triggered by the onload event? It appears that the answer might lie within the question itself... :) Is this true?

Thank you!

Answer №1

When it comes to triggering events in JavaScript, document.onload should be used only when all DOM nodes are ready, not necessarily waiting for all assets to fully load.

There seems to be a misconception at play here. Let's clarify that misunderstanding.

What is the purpose of creating self-executing functions with document.onload?

The truth is, there actually isn't a predefined event called document.onload. This is simply an arbitrary property name without any inherent functionality.

If you assign a function to this property, it will not automatically run when the document loads. Instead, if you immediately invoke the function and store its return value on the property, the function will execute before the DOM is ready. Nothing special will happen to the stored value itself.


To effectively execute a function once the DOM is fully loaded, it is recommended to utilize the DOMContentLoaded event:

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("DOM fully loaded and parsed");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transfer the updated variable from a static JavaScript file to Next.js

I am facing a challenge with a conditional render in my component. I am unable to display the value of a variable. In one file, I have all my functions that I export in index.js import FunctionServices from "../services/functionServices" export ...

An error occurred while trying to access properties of null during a promise, specifically when trying to read the 'parentNode' property - triggered by calling router.push({})

After updating my dependencies, I encountered an issue every time I clicked on a button to navigate to the next page. The error message Uncaught (in promise) TypeError: Cannot read properties of null (reading 'parentNode') would appear, even thou ...

The conversion of the input (ImageButton) to jQuery is not possible

Within my gridview, I have ImageButtons that open an edit form. To determine the ID, I need to access the surrounding element (Row). The issue arises when I try to pass 'this' as a parameter in the onClientClick event which triggers a JavaScript ...

How can I use try-catch in JavaScript to call the same function again in the catch block

When encountering a scenario in JavaScript where a Try Catch block fails due to some issue, what is the best approach to handle this and retry the same operation until it is successful? For example: const getMyDetails = async()=>{ try{ await ge ...

I constantly encounter the error message "Unable to access properties of undefined (reading 'map')"

I am in the process of using Nextjs 13 for developing my front end and I have a requirement to fetch a .json file from a URL and utilize it to populate my website through server side rendering. However, I keep encountering an error saying "Cannot read prop ...

Implementing fetch API in middleware in Next.js

Currently, I am utilizing a middleware in Next.js (https://nextjs.org/docs/advanced-features/middleware) for my project. However, I am encountering an issue when trying to send a request to the API. The error message displayed is: "unhandledRejection: Ty ...

Comparing $.fn.fancybox and $.fancybox: What sets them apart?

I'd like to understand the distinction between the two items shown above. In what ways do they differ from each other? ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

What is the best way to retrieve two elements from the same index level that are located in separate parent DIVs?

Take a look at this HTML setup: <div id="container"> <div class="left-column"> <div class="row">Person 1:</div> <div class="row">Person 2:</div> <div class="row">Person 3:</div> </div> ...

Is there a method to introduce a line break for each piece of data that is shown?

I am currently working with an array and have successfully displayed it on the screen. My inquiry is whether it is feasible to insert a line break for each of the data points it presents. { name: "cartItems", label: "Product Name ...

Prioritize loading the JS function before initiating PHP validation

My current challenge involves calling a JavaScript function from PHP upon form submission. The error message I am encountering indicates that the function is not defined. This issue arises because PHP is loaded before JavaScript, resulting in the function ...

Adding graphs dynamically to Dygraphs allows for real-time updates and interactive data

I recently started using Dygraphs for one of my projects and I am still learning how to work with it. After reading through the documentation and looking at a few examples, I noticed that the constructor for Dygraphs requires a div element where the graph ...

What mistakes am I making in this PHP code as I try to work with the select option?

Currently, I am developing a form that involves selecting values. If the user chooses 'yes', I want to display a text box section. However, the code below is not functioning as expected. <select id="gap" name="gap" onclick="gap_textbox();"> ...

Mapbox struggling with performance because of an abundance of markers

I have successfully implemented a feature where interactive markers are added to the map and respond to clicks. However, I have noticed that the performance of the map is sluggish when dragging, resulting in a low frame rate. My setup involves using NextJ ...

Creating a table and populating its cells with values all within the confines of a single function

This section of code aims to create 3 arrays by extracting values inputted by the user from a popup menu in the HTML file. These values are then utilized to populate the table displayed below. var arrM = new Array; var arrT = new Array; var ar ...

Is there a way to maintain scroll position on a dynamically refreshing div?

After searching for hours, I still can't find a solution to my problem. I am using a simple JQuery script to refresh a div and display my PHP output in it. $script = " <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery ...

The NodeJS and Python-Shell .run function fails to display the standard output

I am currently working with NodeJS and a Python script. To retrieve results from my Python script, I have been using Python-Shell which you can find detailed documentation for at: github.com/extrabacon/python-shell Typically, to get prints from the scrip ...

Attempting to modify PHP query following submission of data via Axios in Vue application

Fetching a JSON object through a PHP query from a service known as BullHorn can be done like this: <?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded,externalCategoryID,employmentTy ...

Using jQuery, effortlessly scroll a div to a specific vertical position of your choice

After referring to this previous question: Scrollpane on the bottom, css is hacky, javascript is hard I followed the same scrolling method as explained in the accepted answer. Now there's a new requirement to select a specific item (e.g., through a ...

In Vue Js, the function createUserWithEmailAndPassword does not exist within _firebase_config__WEBPACK_IMPORTED_MODULE_3__.default

My createUserWithEmailAndPassword function seems to be malfunctioning. Here is the code snippet I am using - config.js import firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const firebaseCon ...