call a function when page is loaded

Calling a Function When Page is Loaded in HTML

If you want to execute a particular function when a web page is loaded, there are several ways to do it in HTML. Here are some of them:

Method 1: Using the onload Attribute

The simplest way to call a function when a web page is loaded is to add the onload attribute to the <body> tag and set its value to the name of the function you want to call:


  <body onload="myFunction()">
    ...
  </body>

In this example, the myFunction() function will be called as soon as the web page is fully loaded.

Method 2: Using the window.onload Event Handler

You can also use the window.onload event handler to call a function when the web page is loaded. This method is more flexible than using the onload attribute because it allows you to attach multiple functions to the event:


  <script>
    window.onload = function() {
      myFunction1();
      myFunction2();
      myFunction3();
    };
  </script>

In this example, the myFunction1(), myFunction2(), and myFunction3() functions will be called in that order when the web page is loaded.

Method 3: Using the jQuery Library

If you are using the jQuery library, you can use the $(document).ready() method to call a function when the web page is loaded:


  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script>
    $(document).ready(function() {
      myFunction();
    });
  </script>

In this example, the myFunction() function will be called when the DOM is ready, which means all the HTML elements have been loaded and initialized.

Method 4: Using the DOMContentLoaded Event

The DOMContentLoaded event is fired when the DOM is ready, which means all the HTML elements have been loaded and initialized. You can use this event to call a function when the web page is loaded:


  <script>
    document.addEventListener("DOMContentLoaded", function() {
      myFunction();
    });
  </script>

In this example, the myFunction() function will be called when the DOM is ready.

Conclusion

These are some of the ways to call a function when a web page is loaded in HTML. Choose the method that best suits your needs and coding style.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe