Categories
JavaScript Answers

How to Run a Function When a Page has Fully Loaded?

Spread the love

Sometimes, we want to run some code when our web page is fully loaded.

In this article, we’ll look at how to run a function when a page has fully loaded with JavaScript.

Listen to the load Event

The load event is triggered when a page is fully loaded.

Therefore, we can listen to the load event by attaching an event handler function to it to run code when the page is fully loaded.

For instance, we can write:

window.addEventListener('load', () => {  
  console.log("page is loaded")  
})

We call window.addEventListener to listen to the load event triggered on the page.

In the 2nd argument, we pass in a callback function that runs when the load event is triggered.

Therefore, we should see 'page is loaded' logged when the web page is loaded.

Listen to the DOMContentLoaded Event

Likewise, we can listen to the DOMContentLoaded event which is also triggered when the page is fully loaded.

So we can attach an event handler to it the same we did with the load event.

For instance, we can write:

window.addEventListener('DOMContentLoaded', () => {  
  console.log("page is loaded")  
})

to run the callback in the 2nd argument when the page is fully loaded.

Therefore, we should see 'page is loaded' logged when the web page is loaded.

Set the window.onload Method

We can set the window.onload method to a function we want to run code when the page is fully loaded.

This is because window.onload runs when the page is fully loaded.

To do this, we write:

window.onload = () => {  
  console.log("page is loaded")  
}

We just set the onload property to a function we want to run when the page is loaded.

Therefore, we should see 'page is loaded' logged when the web page is loaded.

Conclusion

There are several ways we can use to run a function when a web page fully loaded with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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