Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are <script>'s not in <head> ok?

I have had this question niggling at the curious bit of my mind for a while now and I thought I'd ask your collective expertise for an answer to this question.

To elaborate on the title, say I have this:

 alert("Some JS outside "); 

Outside the <head></head> tags of my HTML file. My question is whether it's ok to do this or not, and how much it is used like this.

My instincts tell me it's ok - I reckon browsers look through all HTML for <script> tags and interpret it when they see it, so it should be ok, but I'm not all that great with how browsers work.

I'm looking for a definitive (or as close as possible to definitive) answer here - is it fine to do, or not?

EDIT: To save me posting this a bunch of times, I'll say it once here. Thanks very much for all your input people. Up votes to you all! I will have to re-train myself to put JS at the bottom of pages - now that I think about it it's blindingly obvious that scripts at the bottom of the page is way better than the top. Thanks for your help everyone.

like image 426
Bojangles Avatar asked Nov 30 '10 16:11

Bojangles


People also ask

Do script tags need to be in the head?

In general, it does not matter. Scripts end up in the head tag mostly out of tradition.

Does position of script tag matter?

Yes, it does affect the performance of the web page.

What happens if you place script elements in the head?

If it's in the HEAD section, the script will be parsed before any HTML or CSS elements are loaded. If your Javascript references any of the web page's elements, there may be a slight delay in the fancy effects you want to apply, or it may just not work at all.

Can script go in the head?

JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body. JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked.


1 Answers

Best place for your script tags is before your closing body tag.

<html>       <head>       <title>Example</title>       </head>       <body>             Your Content       <script type="text/javascript" src="yourScriptHere.js"></script>       <script type="text/javascript">//Inline scripts etc.</script>       </body> </html> 

That said they can be other places without a problem however the reason you want them at the end is that you want to ensure the page has loaded before execution and you also do not want to stall client download progress making them wait on large scripts.

like image 131
Jason Benson Avatar answered Sep 29 '22 03:09

Jason Benson