Scripts should always be loaded at last and at the bottom of the body so they can access the DOM and the elements.
You can wrap this around your code, so it is executed when eversthing is loaded
document.addEventListener("DOMContentLoaded", function() {
// your code
});
or
document.attachEvent("onreadystatechange", function(){
if (document.readyState === "complete"){
document.detachEvent( "onreadystatechange", arguments.callee );
// your code
}
});
see the official sourcecode of jQuery ready event here: https://github.com/jquery/jquery/blob/master/src/core/ready.js#L81
it calls the completed()-method, when the page is fully loaded
https://stackoverflow.com/a/21814964/753676 and How can I detect DOM ready and add a class without jQuery? give you the same answers
3
solved position of a script tag is influencing the code execution [duplicate]