Does javascript have to be in the head tags?
Asked Answered
I

11

69

I believe javascript can be anywhere (almost), but I almost always see it in between <head></head>. I am using jquery and wanted to know if it has to be in the head tags for some reason or if will break something if I move it. Thank you.

EDIT: Why is it almost always in the head tags?

Instrument answered 31/7, 2009 at 15:43 Comment(5)
Just as a note, if you inspect pages with <script> tags in FireBug you'll see that they get moved to the <head> tag automatically.Paigepaik
the belief that it needs to be loaded before the item it is acting upon.Bursiform
It seems to be good practice to keep all of your script definitions in one place, usually before the rest of the document is loaded. That's a totally subjective comment on my part though.Eduard
On the contrary, some people recommend putting it at the end of your document so that your page will be loaded and displayed first. Google Analytics recommends this.Suitor
@dr: That is not correct at all, if you want to manipulate an item from a script, it must be after that item in the HTML (or must be in an onready handler).Habited
F
40

JavaScript is executed wherever it is found in the document. If you place inline JavaScript in the body, it will be executed when the browser comes to it. If you're using $(document).ready(...) to execute things, then the positioning shouldn't matter. Otherwise, you may find corner cases where it matters. In general, it does not matter. Scripts end up in the head tag mostly out of tradition.

Filler answered 31/7, 2009 at 15:46 Comment(2)
I would argue that it does matter where you put the script tags. See Nate's post ( #1213781 ) for why it is better to put scripts lower in the page.Birthstone
But in order to call $(document).ready(...), jquery has to be loaded first. So, that needs to be loaded and compiled even if the custom functions themselves aren't.Swingeing
B
49

No, it can be anywhere. In fact, it’s sometimes a good idea to put it at the bottom of the document. For an explanation why, see http://developer.yahoo.com/performance/rules.html#js_bottom.

Brynn answered 31/7, 2009 at 15:46 Comment(2)
This website claims that there is a potential tradeoff/downside to putting scripts at the bottom of the document. The claim is that some elements on your website, for example buttons, may be unresponsive until your javascript executes.Chasten
This should be the accepted solution. It is now considered a best practice.Tyrr
F
40

JavaScript is executed wherever it is found in the document. If you place inline JavaScript in the body, it will be executed when the browser comes to it. If you're using $(document).ready(...) to execute things, then the positioning shouldn't matter. Otherwise, you may find corner cases where it matters. In general, it does not matter. Scripts end up in the head tag mostly out of tradition.

Filler answered 31/7, 2009 at 15:46 Comment(2)
I would argue that it does matter where you put the script tags. See Nate's post ( #1213781 ) for why it is better to put scripts lower in the page.Birthstone
But in order to call $(document).ready(...), jquery has to be loaded first. So, that needs to be loaded and compiled even if the custom functions themselves aren't.Swingeing
R
17

Basically, browsers stop rendering page until .js files are completely downloaded and processed. Since they render page progressively as HTML arrives, the later .js files are referenced, the better user experience will be.

So the trick is to include only absolutely crucial scripts in the head, and load remaining ones towards the end of the page.

Ramsey answered 31/7, 2009 at 15:46 Comment(1)
could you drop a reference link to load javascript asynchronously?Kirkcudbright
T
9

Everything stops when the browser reads a script tag until it has processed it. Your page will therefore render quicker if you move the script tags down as far as possible - ideally just before the end body tag. Obviously the total load time will be the same.

You will have to make sure you don't actually call any jQuery functions until jQuery is included of course.

Tubing answered 31/7, 2009 at 15:46 Comment(0)
T
9

And this is why JavaScript is in such a mess and why old StackOverflow posts are a devs worst nightmare. JS changes so quickly these days with a new framework coming out every week and each one is claimed as the bees knees by it's advocates.

Gumbo is right to say a script tag can be referenced anywhere an inline element can but the choice to load an external JS file or include JS code within a tag is a decision made individually on each case. Yes the browser will stop to load JS when it parses and therefore you need to consider how this will affect page load speed and functionality. The current or as of a year ago, mid 2015 (bear in mind the popualar answer was in July 2009 and most devs won't ever read this as they look at answer no.1 and move on!!!) is that given mobile priority to page load speed requires a two request limit to the mobile/cell mast which under 3G gives you a 28k (2x 14kb(yes)) payload, you need to consider (as Google names it) 'paint to screen' of 28k and this should provide the user with enough page content/interactivity to ensure they're on the right page or on the right track, in that 28k. So a Jquery minified is currently 87.6lkb, just ain't gonna cut the mustard!

This is why most mobile page load currently sit for a couple of seconds before loading anything, and that's 4G! Don't do it. Page speed is king and users hit their back button before your JQuery file loads. Under 3G+ a 28k payload will load in <1sec so there is no reason why your page doesn't start loading in that time. Next time you hit a link on your phone, watch the little bar sit and wait while it goes through all the tags on the next page!

So structure your page not on where a 7 year old post on SO says to( it's not wrong just outdated), but where each piece of code is needed and make sure a user can use of he most important aspects of a page before you try to load 6 JS frameworks to implement clever parrallel scrolls and extensive data binding for your contact page.

BTW Google asks you to push JS to the bottom because they supply Google analytics code and this needs to be the very last thing to load.

Think before you code!

Tithonus answered 10/11, 2016 at 21:31 Comment(4)
I'm not sure what you're telling me to do. Maybe an example? Or a diagram of design?Instrument
johnny, in a nutshell loading external or placing inline javascript needs to be done with two conisderations, when the code is required and how it affects the page load speed. These two factors are greatly affected by mobile network users. My other point was regarding understanding how loading code that isn't needed immediately will slow down page load speed unnecessarily referred to a blocking code.Tithonus
Further reading here, developers.google.com/speed/docs/insights/BlockingJS there isn't a single answer and it's a matter of assessing the code and making a decision on all factors.Tithonus
I understand that you were attached to the insulting tone of the post, but reverting the entire edit also removed all the spelling and grammar fixes. Would you be willing to settle for a well written rant?Airdry
G
5

No. SCRIPT is not only categorized as head.misc element but also as special element and thus everywhere allowed where inline elements are allowed. So you can put a SCRIPT wherever inline elements are allowed:

<p>foo <script>document.write("bar")</script></p>

In fact, some recommend to put SCRIPT elements at the end of the BODY just before the closing tag so that the whole document is parsed before the JavaScript is loaded. That is to prevent JavaScript from blocking parallel downloads.

Grumpy answered 31/7, 2009 at 15:49 Comment(0)
M
2

Actually, for performance reasons, you almost always want to put your script tags at the bottom of your page. Why? You want your page structure and your CSS to load first so that the user sees the page right away. Then you want all your behavior driven code to load last. YSlow is a good firefox extension that will show you a grade for performance. One of the items it grades you on is whether you have javascript at the bottom rather than the top.

Molini answered 31/7, 2009 at 15:47 Comment(0)
N
2

Just be careful about the bad effects on latency that you can have, depending on the user's browser and where exactly you place your Javascript in the page -- see just about all that Steve Souders has to say, including the videos of his Stanford lectures, and the fruit of his labors left behind e.g. here (put scripts at the bottom of the page in as much as feasible, etc etc).

Nore answered 31/7, 2009 at 15:49 Comment(0)
E
1
  1. Because you don't want JavaScript mixed with HTML - content with behaviour. Preferably you want it in a separate file.

  2. Having JS elsewhere has advantages and disadventages - it will be executed at different time, for instance, and you can write to the document from javascript located in the body.

Extenuate answered 31/7, 2009 at 15:46 Comment(0)
P
0

It can go in the head or body tag. Just keep in mind that it will execute whenever is read and not necessarily when the document is finished loading. Take a look here.

Pantalets answered 31/7, 2009 at 15:46 Comment(0)
M
0

In some cases, yes the script may not work if its in the wrong location. Some JavaScript needs to be executed after a specific HTML element, others need to be exactly where you want your script output to show, others should be in the head of the document. It really depends on how the code is written. If you are not sure, you should execute your code on window.load or DOMready: http://www.javascriptkit.com/dhtmltutors/domready.shtml

Malapert answered 31/7, 2009 at 15:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.