How to detect when page has loaded with JavaScript

Uncaught TypeError: Cannot read property 'innerHTML' of null

Or a similar error is what we'll get when we try to access an element before its loaded.

To avoid this, we should only access HTML elements when DOM has completely loaded.

How to know when DOM has loaded

Well, there's an event called DOMContentLoaded that we can listen to.

Like this:

document.addEventListener("DOMContentLoaded", function(e) {
    console.log("DOM Loaded, access elements without errors now");
});

Its handy piece of code that you'll see me using often. You can read more about DOMContentLoaded

References:

Thoughts or Suggestions: