What’s up programmer, okay? Let’s learn where to place JS in HTML!
And the answer to where to insert the script it will depend on what will be done with it
So let’s see some cases:
With the script tag
And any JS code between the tags will be executed as soon as it is read
However, this is not a good practice, with rare exceptions such as: insertion of third-party script
And link via script tag insertion through a source (src)
<script> console.log('teste'); </script>
Inserting scripts in the head guarantees that the JS will be read and executed before the HTML elements
That is, as soon as the page loads, the script will be interpreted
The big problem is that if the script files are too big, there may be a delay when the HTML appears
This is because the file needs to be fully loaded before
We can say that it works as a ‘page blocker’
And a problem with this is that we can’t access the HTML elements, as it will generate an error as if the element doesn’t exist
This happens because the file is loaded before the HTML, so to solve this problem we use the form below
This way you ensure that the HTML appears, so the user already has a preview response from the page.
You’ll also be able to access elements with JS that were previously loaded into HTML
So this turns out to be the most chosen way and in a way correct too
A small problem may occur if you have JS manipulations to adjust a layout, for example
Your screen may appear a little disfigured at first as all the HTML is being loaded before the JS
But it shouldn’t be a big problem, just be aware that it can happen.
One idea is to try to make the right page with HTML and CSS, and then perform the manipulations via JS
Using the async attribute in the file load script tag
You do an asynchronous load, that is, without blocking the page
So the script can be added to the head without having to previously mention the problem
The only problem is that we can’t use this script until the file loads.
So, we must ensure that we don’t need the script in these early moments of the page.
<script async src="script.js"></script>
Also the problems and the advantages of each one of them
We have also seen that adding it to the end of the body has more advantages than other ways
And also the downside, which is a possible misconfiguration of the page when loading, it’s not that impactful
And most of the times it may not even happen