Where is it advisable to put the script tag?

I’ve heard that <script> tag and the </script> work faster when they’re put at the end of the body tag, however, I have also read that the <script> ,</script>,<style> and </style> tags are supposed to be used within the head of a document. What’s more advisable?

The reason it was recommended to put <script> tags at the end of the <body> was so the scripts wouldn’t stop the browser from parsing the HTML. When a browser gets to a <script> tag it stops everything else and loads the file for that <script> tag and then evaluates it. Thus, if you put the <script> tag in the <head> or at the beginning of the <body> then the user would have to wait longer for the HTML to render possibly leaving them staring at a blank page for a while.

Nowadays this isn’t really a concern any more because you can force the browser to download/evaluate JS files asynchronously by using the async or defer attribute on the <script> tag:

And here’s a pictorial representation of these attributes:

So as long as you use one of those attributes you can put the <script> tag wherever you want. Be advised, these attributes only work for <script> tags loading external JS file (i.e. the src attribute is pointing to a file).

4 Likes

If you put the script tag in the head and your javascript file references html elements then you can have problems. Because the script loads before the html does, the html elements that you referenced won’t exist yet.

I’ve not tried it with async and defer, so I’m not sure how it works. I always just put the script tags at the end of the body and it works fine.

Hope this helps.

1 Like

Thanks @Jill-Ann and @bbsmooth , by the way, are async and defer a part of the FCC Curriculum?

no, they are not part of the curriculum, a lot of stuff is not part of the curriculum and you will find when consulting documentation, googling for specific issues, or learning from other sources

1 Like

Thank You! I know it’s irrelevant to the thread’s topic, but I’d like to know about some of the important things which the curriculum has missed out on.

the curriculum cover the basics, you can take a look at documentation about the languages to see what else is there

1 Like

Definitely. No matter where you put the <script> tags you should always make sure that any JS that depends on HTML elements being available does not run until those elements are available.

1 Like