Explain Codes LogoExplain Codes Logo

How to run a function when the page is loaded?

javascript
event-listeners
window.onload
defer-attribute
Alex KataevbyAlex KataevΒ·Jan 14, 2025
⚑TLDR

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:

document.addEventListener('DOMContentLoaded', function() { // Now that I'm ready, it's showtime! 🎭 alert('DOM is fully loaded and parsed'); });

For processes that rely on all resources loading (such as images, stylesheets, etc.), you will need to use window.onload:

window.onload = function() { // All dressed up and ready to go! πŸ‘— πŸ‘” alert('All resources finished loading!'); };

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:

function codeAddress() { // Code: It's the new black! }

Then assign it to window.onload before the window gets to work:

window.onload = codeAddress;

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:

$(document).ready(function() { // On your marks... get set... CODE! });

3. Away with Onload Onslaught!

Expecting multiple onload handlers? Ensure non-collision with addEventListener or attachEvent (for our old friend, Internet Explorer):

function otherFunction() { // The other half of the dynamic duo! } window.addEventListener('load', codeAddress); // Batman window.addEventListener('load', otherFunction); // Robin

4. The Anonymous Function: Unnamed Yet Not Unimportant

Have code that needs to be executed immediately? Use an anonymous function:

(function() { // I may be anonymous, but I'm here to party! πŸŽ‰ })();

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:

<script src="yourscript.js" defer></script>

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.