Use DOMContentLoaded when the <script> code interacting with DOM is included in the <head> section. If not wrapped inside the DOMContentLoaded callback, the code will throw errors like
Cannot read something of
null
document.addEventListener('DOMContentLoaded', function(event) {
// Code that interacts with DOM
});
https://html.spec.whatwg.org/multipage/syntax.html#the-end
DOMContentLoadedAn alternative (suitable for IE8)
// Alternative to DOMContentLoaded
document.onreadystatechange = function() {
if (document.readyState === "interactive") {
// initialize your DOM manipulation code here
}
}
https://developer.mozilla.org/en/docs/Web/API/Document/readyState