How do I call a JavaScript function on page load?
Here is how to trigger a JavaScript function immediately when the HTML document is ready:
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
:
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:
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:
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.
Solid references
- Window: load event - Web APIs | MDN — The ABCs of browser
load
events in JavaScript. - Difference between DOMContentLoaded and load events - Stack Overflow — Get to know the Pros and Cons of
DOMContentLoaded
vsload
. - .ready() | jQuery API Documentation — Learn about jQuery's
.ready()
method and its relation to native JS solutions. - EventTarget: addEventListener() method - Web APIs | MDN — A deep dive into the
addEventListener()
method. - Script Tag - async & defer - Stack Overflow — Everything you need to know about script loading attributes:
async
anddefer
. - Using promises - JavaScript | MDN — A step-by-step guide on handling asynchronous operations with Promises.
- Loading Third-Party JavaScript – web.dev — Learn to optimize the efficiency when loading third-party scripts.
Was this article helpful?