I am sure you might come across this simple format/ template whenever you start working on any new project.
As soon as we get this, we simply add styles.css in meta tag (line 7 in below image) and app.js just before the closing of body tag (line 14 ).
But have you ever think why we even do exactly this and not opposite or not any other way..? well, this blog will answer all such questions.
But it’s not so cleaver way to write JS in HTML file as it create clutter and it may lead ambiguity while debugging the code or updating existing file. so we use —
Now, Magic starts… Hang on
The position of script tag and where we link CSS inside the HTML document plays very important role in loading our web page.
When we place CSS stylesheet at bottom — before the end of body tag
The code runs top to bottom, line by line and when it reach at line no. 11 it prints the heading with normal black text (browser prints “Hello” here) and then script tag hits and we get alert. If we dismiss the alert then it goes to next line where we linked CSS file, which then gets executed and changes the color of text from black to red. So, we always put CSS file at the top (usually below the title)
But at this stage it is not able to find <h1> tag, So we get an error in console — cannot set property ‘innerHTML’ of ‘null.’
which means <h1> isn’t exists yet. The reason is : execution is happening top to bottom , line by line. We are on line 7 of HTML and <h1> tag is below it (on line 12) so it returns null.
…So, the best practice is to put script at the end and just before closing of </body> tag. By doing this, all the content of our website gets loaded first which in turn makes our website to load faster.
Thanks for reading !
Happy Coding !