Since the browser processes the html-page strictly from top to bottom, when inserting the script you need to be sure that the elements you are accessing will be available at the time the script is executed.
There are two ways:
Place script tags that work with the dom-tree ( read: elements ) at the very bottom of the page, namely, before </body>
You can post anywhere, but the code that works with elements can only be called when DOMContentLoaded
or load
events DOMContentLoaded
, for example:
window.addEventListener('DOMContentLoaded', function() { // Ваш код });
In general, the universal way of placing resources on the page is when the styles are at the top, at the head
, and the js code is at the bottom.
There are several reasons:
- Styles are loaded before the page is displayed and the page will be immediately displayed with the styles. What will happen otherwise, you will understand simply by turning off the styles on the page
- The javascript code needs to be loaded and executed, this may cause an additional delay.
- Your case: when the item is not there yet, but the code is looking for it.
Here's a great javascript site , “go through” it and save yourself a lot of time.
body
. - meine