How to run a function when the page is loaded?
To trigger a function as soon as the HTML document is fully loaded, use the DOMContentLoaded
event write an anonymous function inside the event listener for immediate execution as soon as the DOM is parsed:
For processes that rely on all resources loading (such as images, stylesheets, etc.), you will need to use window.onload
:
Ensure your functions are defined before being assigned to the window.onload
event or the DOMContentLoaded
event to avoid hiccups down the line. Plus, you can give your HTML and JavaScript some personal space by storing functions in external JavaScript files.
Handling the Load: Advanced Techniques
1. When in Early, Prepare for the Day
In your Javascript file, pre-define the function like:
Then assign it to window.onload before the window gets to work:
2. jQuery's Secret Sauce
If you're using jQuery, employ $(document).ready()
methodβit's got the bling and also doesn't lean on the <body>
tag:
3. Away with Onload Onslaught!
Expecting multiple onload handlers? Ensure non-collision with addEventListener
or attachEvent
(for our old friend, Internet Explorer):
4. The Anonymous Function: Unnamed Yet Not Unimportant
Have code that needs to be executed immediately? Use an anonymous function:
Dive Deeper: Practical Tips
1. Keep the Files On Their Own Islands
Avoid using inline event handlers like <body onload="functionName();">
because that's against our motto -- separation of concerns.
2. Don't Wait in Line, Defer!
Place the script in the <head>
section but want it to wait for an invite? Send in the defer attribute:
3. The Race of Event Listeners: Order Matters
Got multiple event listeners for window.onload
on the field? They'll run the race in the same sequence you lined them up.
4. All Browsers Welcome!
Choose between window.addEventListener
and window.attachEvent
based on your audience's browsers. Remember that addEventListener
is the favored method, while attachEvent
is the IE's legacy.
Was this article helpful?