Home >Web Front-end >JS Tutorial >How to Execute JavaScript Functions When a Page Fully Loads, Including Images?
Question:
How can I trigger a JavaScript function to run only after all elements on a page, including images, have finished loading?
Answer:
The solution lies in utilizing the load event. Unlike the DOMContentLoaded event, which occurs when the HTML document has been parsed and the DOM tree is ready, the load event waits until all resources, including images, have loaded. This makes it ideal for executing code when the entire page is fully loaded.
Implementation:
To execute a function when the page has fully loaded, you can use the following code:
<code class="js">window.addEventListener('load', function () { // Your code here will run when the page is fully loaded });</code>
Example:
For instance, if you want to display a message in an alert box when the page is fully loaded, you can use the following code:
<code class="js">window.addEventListener('load', function () { alert("It's loaded!"); });</code>
By using the load event, you ensure that your JavaScript code is executed only after all page elements, including images and other resources, have finished loading. This helps prevent issues that may arise due to premature execution of code before the page is fully loaded.
The above is the detailed content of How to Execute JavaScript Functions When a Page Fully Loads, Including Images?. For more information, please follow other related articles on the PHP Chinese website!