I’m currently executing an external script using a <script>
tag inside the <head>
. However, since the script runs before the page content is fully loaded, I can’t access elements in the <body>
and other parts of the page.
Is there a way to use JavaScript on page load to trigger my script only after the HTML has been fully downloaded and is available in RAM? What event should I hook into for this?
Inline defer in your tag
<script src="your-script.js" defer></script>
Why it’s smart:
Adding defer tells the browser: “Download this JS file now, but don’t run it until the whole HTML doc is parsed.” You can safely reference DOM elements without worrying.
It’s like the quiet genius of JavaScript on page load techniques, no extra code, just the right attribute.
Use DOMContentLoaded for faster execution : It waits until just the HTML is parsed, no need to wait for images or CSS files.
If you’re only dealing with DOM elements (not waiting on big assets), this is the JavaScript on page load go-to for speed.
document.addEventListener("DOMContentLoaded", function () {
// Your code here
});
Use window.onload : This method ensures everything is loaded, including images, styles, and subframes, before your JavaScript fires. It’s the most classic and full-page-safe JavaScript on page load trick, great when you rely on external assets being ready.
window.onload = function () {
// Your code here
};