Javascript document onload addeventlistener

JavaScript onload

Summary: in this tutorial, you will learn how to handle the load event that fires on the document, image, and script elements in JavaScript.

The window’s load event

For the window object, the load event is fired when the whole webpage (HTML) has loaded fully, including all dependent resources, including JavaScript files, CSS files, and images.

To handle the load event, you register an event listener using the addEventListener() method:

window.addEventListener('load', (event) => < console.log('The page has fully loaded'); >);Code language: JavaScript (javascript)

Or use the onload property of the window object:

window.onload = (event) => < console.log('The page has fully loaded'); >;Code language: JavaScript (javascript)

If you maintain a legacy system, you may find that the load event handler is registered in of the body element of the HTML document, like this:

html> html> head> title>JS load Event Demo title> head> body onload="console.log('Loaded!')"> body> html>Code language: HTML, XML (xml)

It’s a good practice to use the addEventListener() method to assign the onload event handler whenever possible.

Читайте также:  Исходники ботов телеграмм python

The image’s load event

The load event also fires on images. To handle the load event on images, you use the addEventListener() method of the image elements.

The following example uses the load event handler to determine if an image, which exists in the DOM tree, has been completely loaded:

html> html> head> title>Image load Event Demo title> head> body> img id="logo"> script> let logo = document.querySelector('#logo'); logo.addEventListener('load', (event) => < console.log('Logo has been loaded!'); >); logo.src = "logo.png"; script> body> html> Code language: HTML, XML (xml)

You can assign an onload event handler directly using the onload attribute of the element, like this:

img id="logo" src="logo.png" onload="console.log('Logo loaded!')"> Code language: HTML, XML (xml)

If you create an image element dynamically, you can assign an onload event handler before setting the src property as follows:

window.addEventListener('load' () => < let logo = document.createElement('img'); // assign and onload event handler logo.addEventListener('load', (event) => < console.log('The logo has been loaded'); >); // add logo to the document document.body.appendChild(logo); logo.src = 'logo.png'; >); Code language: JavaScript (javascript)
  • First, create an image element after the document has been fully loaded by placing the code inside the event handler of the window’s load event.
  • Second, assign the onload event handler to the image.
  • Third, add the image to the document.
  • Finally, assign an image URL to the src attribute. The image will be downloaded to the element as soon as the src property is set.

The script’s load event

The element also supports the load event slightly different from the standard ways. The script’s load event allows you to check if a JavaScript file has been completely loaded.

Unlike images, the web browser starts downloading JavaScript files only after the src property has been assigned and the element has been added to the document.

The following code loads the app.js file after the page has been completely loaded. It assigns an onload event handler to check if the app.js has been fully loaded.

window.addEventListener('load', checkJSLoaded) function checkJSLoaded( ) < // create the script element let script = document.createElement('script'); // assign an onload event handler script.addEventListener('load', (event) => < console.log('app.js file has been loaded'); >); // load the script file script.src = 'app.js'; document.body.appendChild(script); >Code language: JavaScript (javascript)

Summary

  • The load event occurs when the document has been completely loaded, including dependent resources like JavaScript files, CSS files, and images.
  • The and elements also support the load event.
  • Use the addEventListener() method to register an onload event handler.

Источник

Window: load event

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets, scripts, iframes, and images. This is in contrast to DOMContentLoaded , which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

This event is not cancelable and does not bubble.

Note: All events named load will not propagate to Window , even with bubbles initialized to true . To catch load events on the window , that load event must be dispatched directly to the window .

Note: The load event that is dispatched when the main document has loaded is dispatched on the window , but has two mutated properties: target is document , and path is undefined . These two properties are mutated due to legacy conformance.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("load", (event) => >); onload = (event) => >; 

Event type

Examples

Log a message when the page is fully loaded:

.addEventListener("load", (event) =>  console.log("page is fully loaded"); >); 

The same, but using the onload event handler property:

.onload = (event) =>  console.log("page is fully loaded"); >; 

Live example

HTML

div class="controls"> button id="reload" type="button">Reloadbutton> div> div class="event-log"> label for="eventLog">Event log:label> textarea readonly class="event-log-contents" rows="8" cols="30" id="eventLog">textarea> div> 
body  display: grid; grid-template-areas: "control log"; > .controls  grid-area: control; display: flex; align-items: center; justify-content: center; > .event-log  grid-area: log; > .event-log-contents  resize: none; > label, button  display: block; > #reload  height: 2rem; > 

JavaScript

const log = document.querySelector(".event-log-contents"); const reload = document.querySelector("#reload"); reload.addEventListener("click", () =>  log.textContent = ""; setTimeout(() =>  window.location.reload(true); >, 200); >); window.addEventListener("load", (event) =>  log.textContent += "load\n"; >); document.addEventListener("readystatechange", (event) =>  log.textContent += `readystate: $document.readyState>\n`; >); document.addEventListener("DOMContentLoaded", (event) =>  log.textContent += `DOMContentLoaded\n`; >); 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 8, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How do I call a JavaScript function on page load

Accessing various functionalities upon page load is required in many web pages and websites to ensure the working of various implemented algorithms. Moreover, while performing automated testing of a website, this feature is very helpful in configuring the working of various operations inside a function and debugging them.

This article will demonstrate the methods to access a function on page load in JavaScript.

How do I call/invoke a function on page load in JavaScript?

To call a JavaScript function on page load, the following approaches can be utilized:

We will now discuss each of the mentioned approaches one by one!

Method 1: Invoke a JavaScript Function Upon Page Load Using window.onload Event

The “window.onload” event occurs when the entire page along with its content loads. More specifically, this event can be applied to access a specific function upon the page load.

In the given syntax, “function” refers to the function that gets invoked when the window gets loaded.

The following example explains the discussed concept.

Example

In the following example, initialize the two variables with the given integer values:

Now, define a function named “pageonLoad()” and place the created variables as its argument. Also, return the addition of the specified values against the variables:

function pageonLoad ( load1, load2 ) {

Finally, apply the “window.onload” event such that when the page loads, the function is accessed, and the sum of the values is returned:

console. log ( «The resultant value is:» , )

console. log ( pageonLoad ( load1,load2 ) ) ;

The corresponding output will be:

The above output is a result of page onloading and accessed functions at the same time.

Method 2: Access a Function on Page Load in JavaScript Using

document.addEventListener() Method

The “document.addEventListener()” method merges an event handler to a document. This method can be implemented to add the specified event for loading the page and calling a particular function in return.

In the above syntax, “event” refers to an event that will trigger and invoke the specified “function”.

Look at the following example.

Example

First, assign the specified id named “load” to the div element:

Next, access the created container by passing its id to the “document.getElementById()” method:

After that, add an event named “DOMContentLoaded” using the “document.addEventListener()” method in order to load the page and access the function pageonLoad():

Finally, define a function named “pageonLoad()”. Here, display the following messages on the alert dialog box and on the Document Object Model(DOM) respectively upon the page load:

alert ( «Function Call on the page load.» ) ;

load. innerHTML = «Function body executed successfully on page load.»

Method 3: Call a Function on Page Load in JavaScript Using body onload Event

The “body onload” event executes the specified function when the page loading process gets complete. This technique can be applied to access multiple functions by placing them in a resultant function’s arguments and performing the desired functionality upon the page load.

In the above syntax, “function()” refers to the function which will be called upon the page load.

The following example will clarify the concept.

Example

Firstly, apply the “body onload” event redirecting to the specified function “execute()”:

Next, define a function named “pageonLoad1()” which returns a value:

Similarly, define a function named “pageonLoad2()” and return the specified value:

Now, define a function named “pageonLoad()” having the above defined functions as its arguments. In this function, both the values returned from the accessed functions will be multiplied and returned:

function pageonLoad ( pageonLoad1, pageonLoad2 ) {

return pageonLoad1 ( ) * pageonLoad2 ( ) ;

Lastly, the defined function “execute()” will access the function “pageonLoad()” and log its functionalities(multiplication of both numbers):

console. log ( «The resultant value is: » )

console. log ( pageonLoad ( pageonLoad1,pageonLoad2 ) ) ;

We have explained the methods to call a JavaScript function on page load.

Conclusion

To call a function on page load using JavaScript, apply the “window.onload()” event to access the function upon the page load, the “document.addEventListener()” method to add a particular event for loading the page or the “body onload” event to merge the functionalities of functions in a single function. This manual demonstrated the methods to access a function on page load in JavaScript.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.

Источник

Оцените статью