Why are JS scripts usually place in the header of a document? - javascript

Why are JS scripts usually place in the header of a document? Is it required by standards, or is it just a convention with no particular reason?

See http://developer.yahoo.com/performance/rules.html#js_bottom
Although past practice has often been to place them in the header for the sake of centralizing scripts and styles (and the like), it is advisable now to place the scripts at the bottom to improve loading speed of the rest of the page.
To quote:
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.

A <script src="url"></script> will
block the downloading of other page
components until the script has been
fetched, compiled, and executed. It is
better to call for the script as late
as possible, so that the loading of
images and other components will not
be delayed.
It depends on what the script is doing. If your code is wrapped in onLoad event then it doesn't matter since it will return almost immediately and not block otherwise you should put it where it fits because the placement does matter.
As for putting it at the end, it does give a little extra time for user to start looking at the page. Just ask yourself a question - does my site work without javascript? If it doesn't, then in my opinion it doesn't mater where you put it since onLoad code will only be executed when the DOM has been fully loaded (that includes binary content like images). If you can use it without javascript then put it at the end so that images can load faster.
Also note that most JS libraries use special code which works around the onLoad problem and uses custom event for this which gets fired once DOM has loaded and doesn't wait for binary data.
Now that I wrote all that, I got a question of my own. Does using say jQuery's
$(document).ready(function () {});
and putting the script tag at the end of page is the same as using onLoad event and putting it at the start?
It should be the same because browser would load all images before loading the script which is the last one in the list. If you know the answer leave a comment (I'm too lazy and it's too late to test it atm).

It's just a convention. It's usually recommended to put scripts at the end of the body so the page can display before loading them, which is always a plus. Also, document.body can't be used until the document is loaded or if you put the script in the body.

Related

The difference between async loading js files and loading in footer [duplicate]

Where is the best place to put Jquery code (or separate Jquery file)? Will pages load faster if I put it in the footer?
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.
EDIT: Firefox does support the DEFER attribute since version 3.6.
Sources:
http://www.w3schools.com/tags/att_script_defer.asp or better:
http://caniuse.com/#feat=script-defer
All scripts should be loaded last
In just about every case, it's best to place all your script references at the end of the page, just before </body>.
If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer attribute so that the browser knows to download your scripts after the HTML has been downloaded:
<script src="my.js" type="text/javascript" defer="defer"></script>
Edge cases
There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head> tag without the defer attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.
Further caveats
There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.
Only load jQuery itself in the head, via CDN of course.
Why? In some scenarios you might include a partial template (e.g. ajax login form snippet) with embedded jQuery dependent code; if jQuery is loaded at page bottom, you get a "$ is not defined" error, nice.
There are ways to workaround this of course (such as not embedding any JS and appending to a load-at-bottom js bundle), but why lose the freedom of lazily loaded js, of being able to place jQuery dependent code anywhere you please? Javascript engine doesn't care where the code lives in the DOM so long as dependencies (like jQuery being loaded) are satisfied.
For your common/shared js files, yes, place them before </body>, but for the exceptions, where it really just makes sense application maintenance-wise to stick a jQuery dependent snippet or file reference right there at that point in the html, do so.
There is no performance hit loading jquery in the head; what browser on the planet does not already have jQuery CDN file in cache?
Much ado about nothing, stick jQuery in the head and let your js freedom reign.
Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?
There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.
Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.
In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.
Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.
Standard practice is to put all of your scripts at the bottom of the page, but I use ASP.NET MVC with a number of jQuery plugins, and I find that it all works better if I put my jQuery scripts in the <head> section of the master page.
In my case, there are artifacts that occur when the page is loaded, if the scripts are at the bottom of the page. I'm using the jQuery TreeView plugin, and if the scripts are not loaded at the beginning, the tree will render without the necessary CSS classes imposed on it by the plugin. So you get this funny-looking mess when the page first loads, followed by the proper rendering of the TreeView. Very bad looking. Putting the jQuery plugins in the <head> section of the master page eliminates this problem.
Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .
I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.
and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.
For me jQuery is a little bit special. Maybe an exception to the norm. There are so many other scripts that rely on it, so its quite important that it loads early so the other scripts that come later will work as intended. As someone else pointed out even this page loads jQuery in the head section.
Just before </body> is the best place according to Yahoo Developer Network's Best Practices for Speeding Up Your Web Site this link, it makes sense.
The best thing to do is to test by yourself.

JavaScript in <head> or just before </body>?

I am about to embark on a new web project and I plan to put some JavaScripts in the <head> and also some before </body>, using the following scheme:
Scripts that are essential for the UX of the page: in the <head>. As I've picked up perusing the web - scripts in the <head> is loaded before the page loads, so it would make sense to put scripts that are essential to the user experience there.
Scripts that are non-essential to the design and UX (Google Analytics scripts etc.): before the </body>.
Is this a sensible approach?
Another approach would be to put all the scripts in the <head> and add defer attributes to the non-essential scripts. However, I read that older versions of Firefox don't pick up the defer attribute.
I think a lot of developers run JavaScript just before the </body> so that it is run after all the elements have been rendered.
However, if you organise your code correctly, the position on the page doesn't matter.
For example, when using jQuery, you can ensure the code isn't run until the page and its elements are fully rendered by doing the following:
$(document).ready(function(){
//Code here
});
Then the script reference can be put in the head tag.
Script tags should be referenced just before </body>. This prevents render blocking while the scripts load and is much better for site perception speed.
No obtrusive JavaScript should be used when using this technique.
JavaScript code should be placed at the end of the document so that it doesn't delay the parallel loading of page elements. This does then require that the JavaScript code is written in a specific way, but it does improve the speed of page loads.
Also, ideally you could host references like this under a different (sub)domain. References to jQuery should be pointed to Google's CDN too.
See Best Practices for Speeding Up Your Web Site for more information.
One of the reasons you'd want to put scripts before the </body> is if they manipulate the DOM without user interaction, so you'll need the DOM to be loaded in order to be manipulated. Another way to do that is to add an event listener and run the scripts when the page has loaded, but this will require additional code, which might get complicated if you have a lot of scripts, especially ones you haven't written yourself. Putting them at the end of the page also will speed up page load, though in the case of DOM manipulating scripts you might get some not-so-pretty results from that.
I'd say that's perfectly sensible. As you said, as long as you don't move essential scripts (e.g. jQuery, Modernizr, etc., etc.) out from the <head>, you shouldn't have problems.
Moving non-essential scripts to the bottom of the page should help with the perceived loading speed (that and minimizing / concatenating scripts).
It all depends on what you mean by "essential for UX". I agree with having Modernizr appear early for example, but not everything needs to load straight away. If you're trying to avoid a flash of unstyled text (FOUT), that's a good reason. Similarly, if you have scripts that affect how the page looks before the user does anything, you should load those early.
Don't forget though, speed is part of UX. There's no advantage in having some jQuery interaction ready to run when the user can't see the content it applies to yet. The difference between loading the scripts at the start of the end is a matter of seconds. If you let the page load first, the user will be using those seconds to take the page in, allowing you to load scripts unobtrusively.
Your page will load faster if you move scripts to the bottom of the page, and that makes a difference to your pagerank these days.
Also, some versions of Internet Explorer will throw errors if you try to run a script before the element it refers to has loaded.
Like Ed says, your scripts should be stored in a separate file, and in as few files as possible.
Put the JavaScript code in a separate file and place a link to it in the head part of the HTML.

Javascript non-blocking scripts, why don't simply put all scripts before </body> tag?

In order to avoid javascript to block webpage rendering, can't we just put all all our JS files/code to be loaded/executed simply before the closing </body> tag?
All JS files and code would be downloaded and executed only after the all page has being rendered, so what's the need for tricks like the one suggested in this article about non blocking techniques to load JS files. He basically suggests to use code like:
document.getElementsByTagName("head")[0].appendChild(script);
in order to defer script laod while letting the webpage to be rendered, thus resulting in fast rendering speed of the webpage.
But without using this type of non-blocking technique (or other similar techniques), wouldn't we achieve the same non-blocking result by simply placing all our JS files (to be loaded/executed) before the closing </body> tag?
I'm even more surprised because the author (in the same article) suggests to put his code before the closing </body> tag (see the "Script placement" section of the article), so he is basically loading the scripts before the closing </body> tag anyway. What's the need for his code then?
I'm confused, any help appreciated, thanks!
UPDATE
FYI Google Analytics is using similar non-blocking technique to load their tracking code:
<script type="text/javascript">
...
(function()
{
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = 'your-script-name-here.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s); //why do they insert it before the 1st script instead of appending to body/head could be the hint for another question.
})();
</script>
</head>
Generally saying no. Even if scripts will be loaded after all the content of the page, loading and executing of the scripts will block the page. The reason for that is possibility of presence of write commands in your scripts.
However if all you want to achieve is the speed of loading page contents, the result of placing script tags right before </body> tag is the same as for creating script tags dynamically. The most significant difference is that when you load scripts in common static way they are executed one by one, in other words no parallel execution of script file (in old browsers the same true is for downloading of the script too).
If you want asynchonous scripts.
Use the (HTML5) async tag if it is availble in the browser you're in. This is what Google Analytics is doing in the code you posted (specifically the line ga.async = true MDN Link, scroll down for async).
However, this can cause your script to load at arbitrary times during the page load - which might be undesirable. It's worth asking yourself the following questions before choosing to use async.
Don't need user input? Then using the async attribute.
Need to respond to buttons or navigation? Then you need to put them at the top of the page (in head) and not use the async tag.
Async scripts run in any order, so if your script is depending on (say) jQuery, and jQuery is loaded in another tag, your script might run before the jQuery script does - resulting in errors.
Why don't people put things at the bottom of the body tag? If the script is taking enough time to load that it's slowing/pausing the load of the website, it's quite possible that that script is going to pause/hang the website after the website has loaded (expect different behaviour on different browsers) - making your website appear unresponsive (click on a button and nothing happens). In most cases this is not ideal, which is why the async attribute was invented.
Alternatively if your script is taking a long time to load - you might want to (after testing) minify and concatenate your script before sending it up to the server.
I recommend using require.js for minifying and concatenation, it's easy to get running and to use.
Minifying reduces the amount of data that needs to be downloaded.
Concatenating scripts reduces the number of "round-trips" to the server (for a far away server with 200ms ping, 5 requests takes 1 second).
One advantage of asynchronous loading (especially with something like the analytics snippet) is, at least if you would place it on the top, that it would be loaded as soon as possible without costing any time in rendering the page. So with analytics the chances to actually track a user before he leaves the page (maybe before the page was fully loaded) will be higher.
And the insertBefore is used instead of append, because if I remember correctly there was a bug (I think in some IE versions, see also link below theres something in the comments about that).
For me this link:
Async JS
was the most useful I found so far. Especially because it also brings up the issue, that even with googles analytic code the onload event will still be blocked (at least in some browsers). If you want this to not happen, better attach the function to the onload event.
For putting the asynchronous snippet on the bottom, that is actually explained in the link you posted. He seems to just do it to make sure that the DOM is completely loaded without using the onload event. So it may depend on what you're scripts are doing, if you're not manipulating the DOM there should be no reason for adding it on the bottom of body. Besides that, I personally would prefer adding it to the onload-event anyway.

the location of javascript in the html?

i am a new learner of javascript, from a book, i know there are three parts to put into javascript in html. one is in <head>...</head>. two is under <body>. the last is under</body>. which is best? what's difference between them?
Depends...
Advantage of having it appear before </body> is the loading of the scripts won't block the parsing of the page (because downloaded scripts are synchronous, because of possible document.write() etc), and you don't need to wait for DOM ready for descendants of the body element.
It is also recommended by Yahoo.
Keep in mind any scripts that modify the same element they are in will trigger Operation aborted in IE6 and 7.
In saying this, however, I place my scripts in head as it seems like a more semantically correct element to place them. It is also easier for maintenance, only having to check in one spot for scripts.
If the downloading of the JavaScript ever became an issue with my sites, however, I would have no issue with placing them before closing </body> tag.
YSlow recommends that you put JavaScript just before the </body> tag. That way they don't block parallel downloads:
http://developer.yahoo.com/performance/rules.html#js_bottom
The current popular convention is to place scripts before the closing </body> tag.
In general, you may want to place a script in the head that will modify the html/css behavior, libraries such as modernizr, html5shiv, etc. are meant to supplant the behavior of CSS, so should be in the <head>. Those are the only scripts I would place in the head section of the document.
Designing your page/site so that scripting isn't needed (to as much of an extent as possible) is the best guideline you can have for a public facing site that may rely on search traffic. If you are developing an intranet/extranet/saas application it isn't as important. What will go along with this is placing scripts at the bottom before the closing body tag, so that all other downloads on the page occur first.
Beyond any of this, having your scripts limited (through minification, and merging) to 6 on a page will allow for scripts to be downloaded simultaneously on browsers that support that behavior. There are tools/techniques that improve on this. Some will bind to the window/load or document/ready events so can be placed anywhere. Having your scripts, css and images on separate CDN domains can help (or spread across a few CDN domains). Avoid having more than 4 total domains in use on a given page as much as possible (excluding common ones such as google analytics, which is likely to already be in the local DNS cache.
I would suggest reading "Even Faster Websites" by Steve Souders for more coverage on this area. Optimizing performance is about more than just where to put your JS.
You should usually put JavaScript in the <head> section (unless certain conditions apply, which are explained below). Some people put it in the body to make quick and dirty changes to the document, but these days it's really not good practice.
Putting it in the head ensures that it loads when the document loads, and it's also easier to manage when it's all in one spot, rather than sprinkled around the page.
Some scripts that may request things from servers are put at the end of the body to prevent "hanging" the page load, but at this point you won't be doing that.
In short, it goes in the <head> section.

Optimal location for javascript includes

I've read that it is better to place your <script> tags at the end of the document. The argument for doing this appears to be that the browser will stall rendering the page below a script tag until it has loaded and and executed the script. If your script tag is at the top of the page, rendering is stalled for a while, which is bad.
However, I am not sure if this is really true any more.
Looking around, I normally see the following locations...
In the <head> of the page or Just inside the <body> tag
Stackoverflow is an example of a site that puts the script tags in the head, and since they are normally rather obsessed with performance, I am starting to wonder if position in the page is important at all.
Last thing in the body element
The other common place to put javascript appears to be right at the very end of the <body> element. I am assuming this means that the page can render while the javascript downloads and gets on with doing its thing.
But which is better?
Does anyone have any thoughts or advice on this? I am looking to try and get our pages to perform and appear to the user as quickly as possible.
Does it matter? What are the advantages of being at the top of the page? Bottom of the page?
It really depends.
There is no catch all answer for this because it depends on what your javascripts are acting on.
Putting scripts at the end of the page is sometimes needed if your acting on a DOM element that needs to be loaded for the script to run. Say you want to focus on a control and your script is:
var mytext = document.getElementById("mytext2");
mytext.focus();
Well in this case you would want it to execute at the end of the page, after mytext2 control has already been loaded by the browser. This is less important for script blocks that only contain functions that are called by events.
If you have a big .js file that contains libraries of functions you may also want to put that at the end of the page so the browser will load the page faster before loading the large .js file.
Google analytics suggests putting their tracker at the end, to make sure the page has been delivered before you count the hits, but in some cases it suggests putting the script into the header too, it works both ways.
So, rule of thumb for me is, HEAD scripts for everything except things that execute in-line and act on DOM objects, or large scripts that you want to load after the page.
Rick Strahl just wrote a great blog on placement of Javascript in .net too:
The only validating way is to include it on the top (in the <head> section), but in the bottom will be faster to load - the rest of the page will load faster if you have script near the bottom, giving the user better response and making the experience better.
The problem is that most web browser stop rendering the HTML of the page until they've fetched and parsed all JavaScript code so far. So if you have a slow-loaded .js file included in the <head>, no HTML will be rendered and images will not even start to download before the .js have been downloaded and parsed, therefore frontend engineers propagate for putting the scripts as far down in the code as possible.
I usually just set a far-future Expires header for my .js files so they are cached in the browser for a long time and then include them in the <head> section. This gives good performance and doesn't look ugly :-)
But if you are serving external .js libraries (that are on other servers than your own), you will probably want them in the bottom because you can't change the Expires-header for other servers and you canät know that the other server always will be responsive.
yeah. Put Scripts at the Bottom
I think the size of the js file is much more important than the location of javascript. I always set highter number of the con-current connection to make sure they download in parallel.
I believe it's better to place script tags just before the closing body tag. Because:
Elements are blocked from rendering if they are below the script.
In IE6, IE7 resources in the page are blocked from downloading if they are below the script.
From this article. Also Yahoo's performance rule 6 is Move Scripts to the Bottom
Google Analytics always used to say to put the script tag at the bottom of the page. I believe the rationale was that if the Google servers ever went down, the page would fail to load if it were in the head (only for IE probably).

Categories

Resources