How to Make JavaScript Execute After Page Load

JavaScript is a powerful scripting language that can make your websites dynamic and interactive.

However, to make sure your code executes properly, it’s important to understand when it will run in relation to when the page loads.

In this Javascript tutorial, we’ll explore several methods to make JavaScript execute after a page has finished loading.


window.onload

The simplest method to run JavaScript code after a page has loaded is to use the window.onload event.

This event fires when all the resources of a page have finished loading.

Here’s an example:

window.onload = function() {
  console.log('The page has finished loading.');
};

It’s important to note that you can only assign a single function to window.onload.

If you need to run multiple functions, you can wrap them inside a parent function, like so:

window.onload = function() {
  function1();
  function2();
};

function function1() {
  console.log('Function 1 has run.');
};

function function2() {
  console.log('Function 2 has run.');
};

addEventListener

Another method to run JavaScript code after a page has loaded is to use the addEventListener method.

This method is a more modern and versatile alternative to window.onload.

Here’s an example:

window.addEventListener('load', function() {
  console.log('The page has finished loading.');
});

Like window.onload, you can attach multiple functions to the load event using addEventListener.

Here’s an example:

window.addEventListener('load', function() {
  function1();
  function2();
});

function function1() {
  console.log('Function 1 has run.');
};

function function2() {
  console.log('Function 2 has run.');
};

$(document).ready

If you’re using jQuery, you can also run JavaScript code after a page has loaded using the $(document).ready method.

This method is equivalent to window.onload but has the advantage of being more concise and easier to read.

Here’s an example:

$(document).ready(function() {
  console.log('The page has finished loading.');
});

Like the other methods, you can attach multiple functions to $(document).ready by wrapping them inside a parent function.

Here’s an example:

$(document).ready(function() {
  function1();
  function2();
});

function function1() {
  console.log('Function 1 has run.');
};

function function2() {
  console.log('Function 2 has run.');
};

Conclusion

In this tutorial, we explored three methods to make JavaScript execute after a page has loaded: window.onload, addEventListener, and $(document).ready.

Each method has its own strengths and weaknesses, so it’s up to you to decide which one is the best fit for your project.

Regardless of the method you choose, it’s important to understand the timing of your code execution in relation to when a page has loaded.