Explain Codes LogoExplain Codes Logo

How do I call a JavaScript function on page load?

javascript
async
callbacks
promises
Alex KataevbyAlex Kataev·Jan 16, 2025
TLDR

Here is how to trigger a JavaScript function immediately when the HTML document is ready:

document.addEventListener('DOMContentLoaded', () => { myFunction(); }); function myFunction() { // Code to execute here }

This uses DOMContentLoaded to execute swiftly after HTML parsing but before all resources (like images) have loaded.

However, if you want all the resources to be loaded before the function is triggered, use window.onload:

window.onload = () => { myFunction(); }; function myFunction() { // Code goes here }

Choose DOMContentLoaded for triggering when HTML is ready or window.onload when the complete page including all resources is loaded.

Package deal - executing multiple functions

What if you want to execute multiple functions on page load? You just need to wrap them all in an anonymous function:

window.onload = () => { firstFunction(); secondFunction(); // Place for any additional functions you wish to run }; function firstFunction() { /* It's a bird... */ } function secondFunction() { /* It's a plane... */ }

This way, your page can don many superpowers all at once.

Remember to fit your solution to your page's structure. If you're stuck with an HTML page without a body element (JSP fragments, I'm looking at you), make sure to place your JavaScript in an appropriate spot.

Going solo - Refusing jQuery's assistance

In cases where you want to roll sans jQuery, fear not. JavaScript has many powerful built-in functions that can achieve what jQuery can, in a more native and often more efficient manner.

And never forget to double-check! Always make sure your function execution is going as planned, on page load.

Complex initializations? No problem

For times when complex initialization drives you up the wall, JavaScript promises or async/await syntax can be your knight in shining armor, effectively handling asynchronous flows or data fetching within window.onload.

Fine-tuning the 'When' of JavaScript execution

You can fine-tune the execution time of your JavaScript by using async or defer with your script tag, or by placing your script tag at the end of the body:

<script defer src="/path/to/your/script.js"></script>

Juggling multiple scenarios

If your page is dynamic, you may need to initialize the state or variables within window.onload or DOMContentLoaded. Always remember to test your code to ensure it executes properly in different environments. The more universal your code, the better.

window.onload = () => { // Initialization of page state setupPage(); // Dynamic content handling populateDynamicContent(); // Event listeners for user interactions setupEventListeners(); // Guess who's coded-out and needs a coffee now? };

Solid references

  1. Window: load event - Web APIs | MDN — The ABCs of browser load events in JavaScript.
  2. Difference between DOMContentLoaded and load events - Stack Overflow — Get to know the Pros and Cons of DOMContentLoaded vs load.
  3. .ready() | jQuery API Documentation — Learn about jQuery's .ready() method and its relation to native JS solutions.
  4. EventTarget: addEventListener() method - Web APIs | MDN — A deep dive into the addEventListener() method.
  5. Script Tag - async & defer - Stack Overflow — Everything you need to know about script loading attributes: async and defer.
  6. Using promises - JavaScript | MDN — A step-by-step guide on handling asynchronous operations with Promises.
  7. Loading Third-Party JavaScript – web.dev — Learn to optimize the efficiency when loading third-party scripts.