call a function when page is loaded
- Published
- Reading time
- 2 min read
- Length
- 345 words
On this page
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.