Main Tutorials

Javascript call a function after page loaded

This article shows how to call a function after a page is loaded in Javascript.

Table of contents:

1. Document: DOMContentLoaded event

In modern JavaScript, the most common way to run code after loading the page is by listening to the document object’s DOMContentLoaded event. This event fires when the initial HTML document has been completely loaded and parsed without waiting for stylesheets, scripts, iframes, and images to finish loading.


document.addEventListener('DOMContentLoaded', function() {
  console.log('The page has loaded!');
  // Your code goes here
});

2. Window: load event

The Window load event is fired when the entire page has loaded, including all dependent resources like stylesheets, scripts, iframes, and images, to be loaded.


window.addEventListener('load', function() {
  console.log('The page fully loaded, including all dependent resources!');
  // Your code goes here
});

3. Javascript calls a function after the page loaded

Below is a complete Javascript example to call a function to replace the text after loading the page (DOM ready).


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript call a function after page load</title>
</head>
<body>

<div id="container">Hello World!</div>

<script>

document.addEventListener('DOMContentLoaded', function() {
  console.log('The page has loaded!');
  updateText();
});

function updateText(){
  // Select the element by ID
  var myElement = document.getElementById('container');

  // Update its text content
  myElement.innerText = 'This is new content';

}
</script>

</body>
</html>

output

javascript call function after page loaded

4. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments