call function when page is loaded

How to Call Function When Page is Loaded in JavaScript

JavaScript allows you to easily perform various DOM manipulations and other tasks by writing user-defined functions on a web page. Generally, we call these functions as an event handler. Sometimes you may need to call these functions immediately after your web page is loaded. In this article, we will learn how to call function when page is loaded in JavaScript.


How to Call Function When Page is Loaded in JavaScript

You can easily call function when your web page is loaded using onload keyword. There are two ways to implement this.


1. Using DOM element

You can add the onload keyword as an attribute in your DOM element, so that it it is triggered when the the element is loaded. Here is an example to call myfunc() function when body element is loaded on your web page.

<body onload="myfunc();">
    ...
</body>

We also need to define the myfunc() function called above in script tag, to handle the above function call.

<script type="text/javascript">
        function myfunc() {
            alert('ok');
        }
    
</script>

Here is the complete code for your reference.

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
           function myfunc() {
            alert('ok');
           }
      
        </script>
    </head>
    <body onload="myfunc();">
       ...
    </body>
</html>


2. Using JavaScript

You can call a function directly from JavaScript, using window.onload property. Here is an example where we define myfunc() function and call it on window.onload.

<script type="text/javascript">
    function myfunc() {
        alert('ok');
        }
    window.onload = myfunc;
</script>

In the above code, we have defined myfunc() function and assigned it to window.onload which is called when the page is loaded.

In the above code, we have learnt how to call function when page is loaded. As described above, you can include the function call within DOM element using its onload attribute, or from your script tag by assigning it to window.onload attribute.

If you are using third party libraries such as jQuery, you can call these functions within $.document.ready() function, which is executed when a page is loaded.

Also read:

How to Match Exact String in JavaScript
How to Convert Column into Rows in Pandas
How to Set/Unset Cookie with jQuery
How to Abort AJAX Request in JavaScript/jQuery
How to Get Value of Text Input Field With JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *