- Add an event listener –
- Add onload to the body tag –
- Defer the script –
<script src="SCRIPT.js" defer>
- Lastly, place the script at the very bottom of the page – Although this is not quite “after page load”.
That covers the basics, but let us walk through some detailed examples in this guide. Read on!
TLDR – QUICK SLIDES
Fullscreen Mode – Click Here
TABLE OF CONTENTS
EXECUTE ON PAGE LOAD
1) EVENT LISTENER
Events should be pretty self-explanatory, even if you have never heard of them before. They are fired whenever something of interest happens – Mouse click, scroll, keypress, video play, and more. In this example, we listen to the
P.S. You can also target the
DOMContentLoaded event. The difference is that
load is fired when everything is fully loaded. But
DomContentLoaded is triggered as soon as all the HTML elements are ready. I.E. Images, CSS, videos may not be fully loaded.
2) BODY ON LOAD
Well, this kind of does the same thing as attaching
addEventListener("load", FUNCTION). When the HTML document is loaded,
onload="demo()" will be triggered.
3) DEFER SCRIPT LOAD
document.getElementById("myTxt").style.color = "blue";
Yes, just add
defer to the
<script> tag, and it will hold until the entire page is done. For those who are confused about the difference between
onloaddoes not mess with the loading order of the script, it simply runs the specified function when the page is ready.
P.S. Please take note that
4) SCRIPT AT BOTTOM (NOT QUITE AFTER PAGE LOAD)
Lastly, just put the scripts at the bottom of the page. This is not quite “after page load”, but it is… After everything else is nearly loaded.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for this guide, and here is a small section on some extras and links that may be useful to you.
WHICH IS THE BEST METHOD?
Personally, I will usually use
window.addEventListener("DOMContentLoaded", FUNCTION) or
defer loading non-critical scripts. But whichever makes the most sense for your own project is the best method.
LINKS & REFERENCES
- Onload – MDN
- Events – Web API – MDN
INFOGRAPHIC CHEAT SHEET
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!