How to run JavaScript after the page has loaded

If you need to wait until your page loads before running some JavaScript, you should listen for DOMContentLoaded:

document.addEventListener("DOMContentLoaded", function() {
// your code here
}

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. — Mozilla Developer Center

In rare cases, you’ll need to wait until all the elements on your page have loaded entirely – meaning that your stylesheets, images, and subframes are finished loading. If that’s the case, you should listen for load. But in most cases, you should be using DOMContentLoaded instead.

I'm Mark Thomas Miller, an engineer, designer, and maker of things.