Why does this javascript function need to be placed after the html code? [duplicate]
Solution 1:
The position of where you place the script tag is indeed important and can have effect your code as you just experienced. Browsers behaves in the way that they parse the HTML from top to bottom, so elements are added to the DOM and scripts are executed as when they are encountered, meaning that order you place the elements and the tags does matters. scripts won't be able to find elements and perform manipulation on them if they appear later in the markup html code because those elements have yet to be added to the DOM.
Let's walk through on what's happening when a browser loads a website with a certain script tag:
- Fetches the HTML page
- Browser start parsing the HTML
- The parser encounters a
script
tag referencing an external script file and requests that file. Meanwhile, the parser blocks (unless the async or defer key word exist) and stops parsing the rest of the HTML. - After some time the script is downloaded and subsequently executed.
- The parser then can continue parsing the rest of the HTML document.
So, in step 4, since the parser didn't yet parse the HTML document, he won't be able to work with the rest of the HTML and that is why your script
tag has to be located at the bottom.