\n\n\nPlace deferred scripts in the section to support a clear separation of HTML and JavaScript.","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Anton Shumikhin","url":"https://explain.codes//author/anton-shumikhin"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2025-02-19T17:30:01.562Z","dateModified":"2025-02-19T17:30:03.105Z"}
Explain Codes LogoExplain Codes Logo

How to make JavaScript execute after page load?

javascript
prompt-engineering
async
defer
Anton ShumikhinbyAnton Shumikhin·Feb 19, 2025
TLDR

Use DOMContentLoaded to run JavaScript as soon as the HTML document has been fully parsed:

document.addEventListener("DOMContentLoaded", function() { // My precious code goes here. // Much like the Ring, this won't be seen until the journey's end });

For scenarios requiring all resources such as images to load, use load:

window.addEventListener("load", function() { // Not just any code...but the chosen code. // Essentially, this is the Nahilismortuosescapicus spell from Harry Potter. });

To set scripts to execute after the HTML is fully parsed not blocking the HTML parsing process, use the defer attribute:

<script src="path-to-your-script.js" defer></script>

Place deferred scripts in the <head> section to support a clear separation of HTML and JavaScript.

Deciding between defer, async, or inline scripts

Discover when to use defer, async, or inline scripts to power-up your site loading speed.

defer attribute

Choose defer for scripts that can wait their turn, executing them after the document is parsed but before firing DOMContentLoaded.

  • Executes scripts in order like a polite British queue.
  • Only affects scripts with an external source (i.e., the src attribute).

async attribute

Use async for scripts that can't wait and need to load as the rest of the page continues parsing.

  • Executes scripts ASAP as they load, relying on their initiative in a 'Bourne Identity' style, order not guaranteed.
  • Great for lone-wolf scripts that don't rely on others.

Inline scripts

Inline <script> tags placed right before the </body> tag execute after the HTML is parsed but does not assure all resources are loaded. They're the can-do spirit of scripts.

Deploying jQuery and ensuring cross-browser support

Deploy the power of jQuery for projects already using it when the DOM is fully at your disposal or the page is fully loaded:

$(document).ready(function() { // The DOM yields to me, like bending the spoon in The Matrix. }); $(window).load(function() { // Page is fully loaded, all assets are ready for world domination... I meant... for use! });

For cross-browser support like a super-secret-agent spy, use addEventListener with a fallback:

function pageLoaded() { // Top-secret code executed here } if (window.addEventListener) { window.addEventListener('load', pageLoaded); // Old reliable } else if (window.attachEvent) { window.attachEvent('onload', pageLoaded); // For that one weird IE in your life }

Advanced techniques for complex loading situations

Sometimes single events are not enough; for these, use these complex-loading survival skills.

Handling multiple onload handlers

For multiple functions that need the post-page load stage, organize them into a solitary onload handler:

function firstFunction() { /* ... */ } function secondFunction() { /* ... */ } window.addEventListener("load", function() { firstFunction(); // Like Mario, it gets the first turn secondFunction(); // Luigi time! });

Using document readiness for unique loading behavior

Customize your loading behavior by checking document.readyState:

document.onreadystatechange = function () { if (document.readyState === "complete") { // The stage is set. It's showtime! } };

Tackling dynamically injected scripts

For scripts dynamically injected into the page (added via JavaScript), ensure they mimic defer behavior:

var script = document.createElement('script'); script.src = "path-to-your-script.js"; script.async = false; // Promise I won't cut in line! document.head.appendChild(script);