In this article, we will learn how to execute a script after loading an element in HTML.
When loading an object, the onload event occurs. Onload is most commonly used within the
element to run a script after the web page has fully loaded all of its content. This can be used for a variety of purposes, such as checking cookies or setting the appropriate page version based on the user's browser.Let’s dive into this article to learn more about executing scripts after loading elements in HTML.
After the element has finished loading, the onload event will occur. To execute a script after the web page has fully loaded, use it with the body element.
The following is the syntax of the onload method.
<body onload="functionToBeExecuted">
In the following example, we use the onload method.
<!DOCTYPE html> <html> <body onload="loadFunction()"> <h1>Welcome To TutorialsPoint</h1> <script> function loadFunction() { alert("Loaded Successfully"); } </script> </body> </html>
When the script is executed, the event is triggered and a "loaded successfully" alert is displayed on the web page.
If the user clicks "OK", the page will load successfully and display the text "Welcome to Tutorial Point".
The onload attribute of the window element is used to execute the script after the web page is fully loaded. Once the web page loads, this feature will be activated by the onload attribute.
The following is the syntax of the window.onload method
window.onload = function exampleFunction() { // Function to be executed }
Consider the following example where we use the window.onload method.
<!DOCTYPE html> <html> <body> <h1>The Best E-Way Learning.</h1> <script> function loadFunction() { alert("Window Loaded Successfully"); } window.onload = loadFunction(); </script> </body> </html>
When running the above script, the output window will pop up, and when the event is triggered on the web page, an alert of "Window loaded successfully" will be displayed.
When the user clicks "OK", the window loads successfully and displays the text "Best Electronic Ways to Learn" on the web page.
The above is the detailed content of Execute a script when the element is loaded in the HTML?. For more information, please follow other related articles on the PHP Chinese website!