How to use onload method In Javascript

The body of a webpage contains the actual content that is to be displayed. The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded. The function that is required to be executed is given here.

Syntax:

<body onload="functionToBeExecuted">

Example: In this example, we have used onload method.

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        How to run a function when the
        page is loaded in javascript ?
    </title>
</head>
 
<body onload="console.log('The Script will load now.')">
     
    <h1 style="color: green">w3wiki</h1>
     
    <b>
        How to run a function when the
        page is loaded in javascript ?
    </b>
     
    <p>
        The script has been executed. Check
        the console for the output.
    </p>
</body>
 
</html>


Output:

Console Output:

How to run a function when the page is loaded in JavaScript ?

A function can be executed when the page loads successfully. This can be used for various purposes like checking for cookies or setting the correct version of the page depending on the user’s browser.

Below are the approaches to run a function when the page is loaded in JavaScript:

Table of Content

  • Using onload method
  • Using window.onload

Similar Reads

Method 1: Using onload method:

The body of a webpage contains the actual content that is to be displayed. The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded. The function that is required to be executed is given here....

Method 2: Using window.onload

...