Using the window.onload Event
The window.onload event is a built-in event in the browser that executes a particular function when the page is fully loaded, including all images, stylesheets, and scripts. This event is widely used to call a JavaScript function on page load. Let's see how to use this event:```window.onload = function() { //Your function code goes here}```
In the above code, we assign the window.onload event to an anonymous function. This function will be executed when all the page contents are loaded. Inside this function, you can write your desired code.Using the body onload Attribute
Another approach to call a JavaScript function on page load is by using the body onload attribute. The body onload attribute is added to the body tag, and this attribute executes the specified function when the page is loaded successfully. Let's see how to use this attribute:```
//Your HTML code goes here```In the above code, we added the onload attribute to the body tag and assigned a specific function name to it. This function will run as soon as the body tag is loaded completely.Using the jQuery $(document).ready() Method
jQuery is a popular JavaScript library used to simplify JavaScript programming. It provides a very convenient way to execute a function on page load. The jQuery $(document).ready() method is used to call a function when the document is ready. Let's see how to use this method:```$(document).ready(function(){ //Your function code goes here});```
In the above code, we use the $(document).ready() method to call our custom function, which will be executed when the document is ready.Using the ES6 Window.addEventListener() Method
The Window.addEventListener() is a modern method used to add an event listener to an element. This method can also be used to call a function on page load. Let's see how to use this method:```window.addEventListener('load', function(){ //Your function code goes here});```
In the above code, we added an event listener to the window object, and the 'load' event will trigger the specified function when the page is loaded successfully.