In all the documentation I see the jQuery script tag beneath <title>
in the head, but then when I go into some other sites (the initializr template is the first off the top of my head), they drop it into the bottom of the body (you know, right before </body>
).
Which of these two is right?
Quoting the YDN Best Practices for Speeding Up Your Web Site:
Put Scripts at the Bottom
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.
An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.
It's funny that people used to say that I should be slapped upside the head for doing that when I said that in 2009 and now it's suddenly a best practice... Some progress.
Well, I think you need to put this inside a $(document).ready(function() {
so that the document is actually ready before you are calling the jQuery. Personally I also put just before the </body>
. Now given that both works, is there a 'right' way, or it's just a question of personal preference?
Would love to listen from experts, though.
Steve Souders' book High Performance Web Sites recommends putting scripts at the bottom, before the </body>
tag. You can also find this documented at the developer.yahoo.com site here. (It's the fourth recommendation in the list.)
I generally put the scripts at the bottom, before my '' tag and have had few issues with this. I've noticed that this helps performance on older browsers like IE7 a lot more than it does with newer ones like FF3.6, Chrome and IE9. The older browsers only support 2 parallel downloads, whereas the newer ones support something 6 connections. The blocking, as a result, isn't as noticeable.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With