Call JavaScript function on page load.

How do I call a JavaScript function on page load?

This tutorial will teach us to call a JavaScript function on page load. In many cases, while programming with HTML and JavaScript, programmers need to call a function, while loading the web page or after the web page load finishes. For example, programmers need to show the welcome message to the user on page load, and the programmer needs to call a JavaScript function after the page load event.

There are various ways to call a function on page load or after page load in JavaScript, and we will look at them one by one in this tutorial.

  • Using the onload event in the tag
  • Using the window.onload Event
  • Using the DOMContentloaded Event

Using the onload event in the tag

The first approach for calling a function on the page load is the use an onload event inside the HTML tag. As you know, the HTML body contains the entire content of the web page, and when all HTML body loads on the web browser, it will call the function from the JavaScript.

Syntax

Follow the below syntax to use onload event in the tag.

Example

In the below example, we have created the JavaScript function named welcomeFunction(). We are calling that function from the tag using the onload event, and it shows the welcome message in the alert box to the users.

      

Methods to call a JavaScript function on page load.

Call the JavaScript function on page load by using onload event in the HTML body tag.

let message = document.getElementById("message"); function welcomeFunction()

When users run the example code, they will give the welcome message in the alert box. When function execution completes, users will get the above output message.

Using the window.onload Event in JavaScript

Here, we have a second approach for calling the function on page load in JavaScript. Every web page contains the window object by default, and the window object represents the global variables. We can access any global variable or function in JavaScript using the window object. In this approach, we will use the onload property of the window object.

By using the window.onload property, users can either call a named function or bind an anonymous function to the window.onload and all code inside the anonymous function will be executed after the page load.

Читайте также:  Java to postgresql jdbc examples

Syntax

Users can follow the below syntax to use the window.onload to call a function on page load.

Function simpleFunction ( ) < // function body >Window.onload = simpleFunction( );

Example

In the below example, we are calling the named function on the page load using the window.onload property.

      

Methods to call a JavaScript function on page load.

Call the JavaScript function on page load by using window.onload event in the JavaScript.

window.onload = simpleFunction( 10, 20 ); // call function with parameters on page load function simpleFunction( num1, num2 )

Using the DOMContentLoaded Event

JavaScript has a cool feature of the event listener, and users can call a function or perform some operation when any event triggers. In this approach, we will use the “DOMContentloaded” event. We will call the desired function using the addEventListener() method in JavaScript. Also, we will apply the event listener to the whole document such that we can call a function on the page load.

Syntax

To call the DOMContentLoaded event, users can follow the below syntax.

document.addEventListener("DOMContentLoaded", function() < // function body >);

Example

The below example demonstrates the use of the DOMContentLoded event to trigger a function call on the page load.

      

Methods to call a JavaScript function on page load.

Call the JavaScript function on page load by using document.addEventListener( ) method.

let message = document.getElementById("message"); document.addEventListener( "DOMContentLoaded", functionCall()); function functionCall()

Users will also see the alert box with the message when the function will be executed.

Conclusion

Here, we have defined three approaches to trigger a function call on the page load. The first approach we can use inside the HTML code, the second one in the JavaScript code, and the third approach is the best approach to achieve our goal.

Furthermore, users can change the event in the third approach to trigger a function on a particular event. One more thing in the last approach is rather than triggering the event listener to the whole document, users can apply it to a specific HTML element also.

Источник

window.onload for executing as soon as page loads

Window Onload

Window.onload function we can use to perform some task as soon as the page finishes loading. This JavaScript function is used in different condition like displaying a print page or directing focus ( keeping the crusher blinking ) to user input field as soon as the page is loaded.

JavaScript Window onload to execute script as soon as page loads and difference between body onload

Using body tag

The other way to achieve the same result is by using onload inside body tag of the page. You can read this article on how to keep the onload event handler to set the focus on input tag once the page loads. �

Let us start some simple example of uses of window.onload function where we will display one Alert box once the page loads.
demo of window onload event →
Here is the script

     

Difference between window.onload function and body tag onload.

wondow.onload is executed when full page is loaded to the browser ( including all images, style , scripts ,CDN etc )
document.onload is executed when DOM is ready ( Not necessarily all connected script, images etc to be downloaded )

We can’t keep any code to access the property set or any other related objects of the elements present in body of the page by using window.onload function.

Читайте также:  Html array to string conversion in

Say we want to select the text present inside a text box as soon as the page loads. This is not possible by using window.onload event but this is possible by using body onload command. The code below will generate error message.

      

plus2net.com

Источник

$(document).ready vs $(window).load vs window.onload

Длительное время мы использовали '$(document).ready' работая с jQuery. Написанный таким образом код начнёт выполняться сразу после того, как будет готов DOM, за исключением картинок. Указанный код будет выполняться непосредственно после готовности DOM, не дожидаясь полной загрузки изображений. Вызов $(document).ready несколько раз приведет к последовательному исполнению вызовов друг за другом. Существуют ещё несколько вариантов записи.

 //Вариант 1 $(document).ready(function() < /** начнёт работу тогда, когда будет готов DOM, за исключением картинок **/ // ваш код >); //Вариант 2 $(function() < /** начнёт работу тогда, когда будет готов DOM, за исключением картинок **/ //ваш код >); //Вариант 3 $(document).on('ready', function()< /** начнёт работу тогда, когда будет готов DOM, за исключением картинок **/ //ваш код >); //Вариант 4 jQuery(document).ready(function()< /** начнёт работу тогда, когда будет готов DOM, за исключением картинок **/ //ваш код >); 

Если мы говорим о $(window).load то код, написанный внутри такой конструкции, начнёт работу когда будет готов весь DOM включая изображения. Такой вызов подойдёт если мы хотим работать с изображениями (расчёт размеров изображения). Данный вызов, как и предыдущий является jQuery событием. Если на нашей странице есть изображения, то сначала мы дождёмся загрузки их всех, а потом будет вызван код.

И ещё кое-что, не путайте событие window load с jQuery методом ajax load.

 // ajax метод загрузки в jQuery $("#elementid").load( "data.html" ); 

Событие onload является стандартным событием в DOM, а описанные выше решения работают только при наличии библиотеки jQuery. Данный вариант имеет такую же функциональность как $(window).load , но является встроенным JavaScript событием. Событие onload происходит, когда объект был загружен. Мы можем сделать такой вызов непосредственно из тега. Например, разместив его в теге изображения и как только оно будет загружено произойдёт вызов события.

Такой вызов возможен как в HTML так и в JS.

 object.onload=function();// объектом здесь может быть window, body и т.д. 

Alert “вызов после загрузки body” будет вызван сразу после того как загрузится body

 // myFunction() будет вызвана после body load function myFunction()

Если рассмотреть пример работы onload после загрузки изображения, то выглядеть все будет как показано ниже

 // myFunction() будет вызвана после загрузки изображения function myImageFunction()

Источник

What is the Window onload event in JavaScript?

With the new advancements in web development, JavaScript is even evolving in different frameworks, which makes life easy for developers. Talking about its use, as of now many famous websites are built on JavaScript which depicts how reliable this language is.

JavaScript has a window onload event to launch certain functions whenever a web page is loaded. The onload event is also used for verification of type and version of visitor’s browser. Further cookies can also be checked through the onload attribute.

The attribute of onload triggers when the object is loaded in HTML. This is to launch the script whenever the associated element loads. In simpler words, we can say that the window onload event is triggered whenever a web page is launched successfully.

Onload event is used with to run a script once its substance (which includes CSS files, images, and scripts) of the page is triggered completely. However, you do not always need a tag. It can be used with other Html elements.

The download.onload launches before the images and external contents, triggered just before the window.onload. Whereas, window.onload starts after the page is completely loaded including CSS, script files, images, and many more.

If you want to manipulate load event in JavaScript, then you need to register event listener through method of addEventListener() as shown in the example below:

window. addEventListener ( 'load' , ( event ) => {

You can also handle the load event through the property of the window object i.e. onload. The example below shows how to use onload property:

Window.onload Event in the head section of HTML

First of all, we are going to present a simple example of a window.onload event. In this example, we simply display an alert message whenever a page is loaded.

alert ( " Hello, you are learning onload event in JavaScript" ) ;

window. onload = js_onload_code ( ) ;

Onload Event in the body section of HTML

Content can be displayed in the body section of HTML. Whenever the webpage is loaded then the event which occurred at that time is named onload event. We can use the onload event in the body section so that we can execute the script.

If you want to use an onload event within the body section then run the following code.

alert ( " Hello, you are learning onload event in JavaScript" ) ;

Window Onload Event in the body section of HTML

The object of the onload window represents the window of the browser. Whenever all the operations are completely loaded then onload property processes the load event. The function which we want to execute is allocated to the handler function of the onload property. Whenever the webpage gets loaded then the function will be executed. We have provided you with an example below.

window. onload = function functionName ( ) {

< b >What is window onload event in JavaScript ?

< p >Script Executed. Now you can check your console to see the output.

window. onload = function your_function_name ( ) {

console. log ( 'Hey, you are learning window onload event in JavaScript. Script will be loaded.' ) ;

Output of Console

If you want to see the output of the console then you have to open devTool by pressing the shortcut keys i.e. CTRL+SHIFT+ I. After opening the Devtool, you will be able to see the console’s output screen as shown below.

Conclusion

We have learned about what window.onload() event is and also learned the syntax of onload event. We briefly discussed several methods of how to write onload events in JavaScript along with an example. To recap, window.onload() event triggers after the web page has been loaded. We also see that the onload event is useful to set the version of browsers and also used to observe the cookies of a web page.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.

Источник

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