Where should I declare JavaScript files used in my page? In <head></head> or near </body>?
Asked Answered
A

12

41

I was reading a tutorial and the author mentioned to include JavaScript files near the closing body tag (</body>) in HTML.

For what type of functionality should I not declare/define JavaScript include in the head section? It makes sense to me include JavaScript like Google Analytics near the closing body tag. Where should I be careful in defining JavaScript include near the closing body tag?

Aegisthus answered 18/6, 2009 at 14:51 Comment(2)
Possible duplicate of What's Pros and Cons: putting javascript in head and putting just before the body closeCiliate
The canonical question is Where should I put <script> tags in HTML markup? (1700 upvotes and 34 answers).Zitazitah
M
43

It will often be argued that for speed purposes you should put script tags right at the end of the document (before the closing body tag). While this will result in the fastest page load, it has some serious downsides.

Firstly, a common idiom with Webpage development is to have a header file, a footer file and your content in the middle. To keep unnecessary JavaScript code to a minimum, you'll often want to put code snippets in individual pages.

If you include jQuery, for example, at the end of the document, your jQuery code snippets (like document ready stuff) must happen after that. That can be awkward from a development point of view.

Secondly, in my experience, because the page load is faster, you can end up noticing certain effects being applied because the page has already loaded by the time they are applied.

For example, if you put a table in a document and right before the body close tag put:

$(function() {
  $("tr:nth-child(odd)").addClass("odd");
});

with appropriate styling, that effect being applied will often be visible. Personally I think that makes for a bad user experience potentially. I think often you're better off having the page load slightly slower (by putting scripts at the top) if you don't get disconcerting visual effects.

I generally advocate effective caching strategies so you only have to download JavaScript files when they change, as in Supercharging JavaScript in PHP (but the principles apply to any language, not just PHP) and still putting scripts at the top. It's far more convenient.

Moire answered 18/6, 2009 at 14:54 Comment(3)
"it has some serious downsides." .. yes, am asking about these. Examples would help. ThanksAegisthus
Care to clarify what those downsides are?Boucher
I've read that twice, but I still don't get it: where should I put my scripts - at the top or at the bottom?Stenophyllous
B
13

By putting them in the <head/> you force the browser to download the files before it can render a page. That causes the perceived load time to slow down.

By placing them in the footer, right before the closing body tag, the browser will not load them until it reaches that point in the parsing of the HTML. That means that the scripts will run later in the page load process but will not block the asset download and rendering process.

Which works best is up to you and how you develop your code.

Bethlehem answered 18/6, 2009 at 14:56 Comment(1)
Yeah, exactly. I'd say in general, you'd want to put them on top (in the <head>) as that's where most people will look.Chateau
P
12

The Yahoo YSlow tool has advice on this:

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.

Paranymph answered 18/6, 2009 at 14:54 Comment(3)
An added bonus of this is if all your scripts come just before </body>, you don't have to set event listeners waiting for the page to finish loading since all elements above the script tag are available for use. No more $(document).ready() for you jQuery users or window.addEvent('domready') for Mootools users.Flange
Qute possibly, although I wouldn't recommend it. Using the listeners will still be safer, and is guaranteed to work.Paranymph
Actually, Firefox 3.5, which will probably be released later this month, supports @defer. See developer.mozilla.org/En/HTML/Element/ScriptHealion
L
4

Google pagespeed have some nice explanation on how to parallelize downloading of scripts.

Still their advice is to put them in the head of your page.

Larochelle answered 18/6, 2009 at 15:4 Comment(0)
N
2

Script tags should generally be in the head section. The exceptions are when they do significant immediate processing that should be delayed until as late as possible in the page load to avoid interfering with the page coming up, as with Google Analytics, or when the script tag's actual placement is a part of its behavior.

Nyctophobia answered 18/6, 2009 at 14:55 Comment(0)
A
1

The reason for declaring near the end is that your page can begin drawing before having to wait to fetch the .js.

Ergo, stuff you would want at the end would have no effect on the page rendering, and vice versa.

Actable answered 18/6, 2009 at 14:54 Comment(0)
R
1

I like to load a small js file in the head, that handles (1) anything that happens before the page is rendered and (2) the loading of other script files after the page loads, or as needed.

Rebhun answered 19/6, 2009 at 1:1 Comment(0)
B
1

I believe it's better to place script tags just before the closing body tag. Because:

It is from this article. Also Yahoo's performance rule 6 is Move scripts to the bottom.

Barometer answered 5/1, 2010 at 17:12 Comment(0)
O
1

The Place of the <script> Element

The script elements block progressive page downloads.
Browsers download several components at a time, but when they encounter an external script, they stop further downloads until the script file is downloaded, parsed, and executed.
This hurts the overall page time, especially if it happens several times during a page load.
To minimize the blocking effect, you can place the script element toward the end of the page, right before the closing tag.
This way there will be no other resources for the script to block. The rest of the page components will be downloaded and already engaging the user.
The worst antipattern is to use separate files in the head of the document:

<!doctype html>
<html>
<head>
    <title>My App</title>
    <!-- ANTIPATTERN -->
    <script src="jquery.js"></script>
    <script src="jquery.quickselect.js"></script>
    <script src="jquery.lightbox.js"></script>
    <script src="myapp.js"></script>
</head>
<body>
...
</body>
</html>

A better option is to combine all the files:

<!doctype html>
<html>
<head>
    <title>My App</title>
    <script src="all_20100426.js"></script>
</head>
<body>
    ...
</body>
</html>

And the best option is to put the combined script at the very end of the page:

<!doctype html>
<html>
<head>
    <title>My App</title>
</head>
<body>
    ...
    <script src="all_20100426.js"></script>
</body>

“JavaScript Patterns, by Stoyan Stefanov (O’Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750.”

Overdevelop answered 19/5, 2012 at 11:58 Comment(1)
My understanding is that CDN-hosted files like jquery.js and bootstrap.js are commonly already in the user's cache, and as such it would reduce load.Randell
R
1

You should put JavaScript right before </body>. Ideally, your HTML should function without JavaScript, so it should be one of the last things loaded.

Bear in mind that you should use CSS to hide elements and not JavaScript. This avoids seeing elements appear and disappear as the page loads.

You may also come across the following problem...

Problem

In this scenario, I'm going to use PHP as an example.

Your footer.php file may currently look like this:

<script src="jquery.js"></script>
<script src="custom.js"></script>
</body>
</html>

But what happens on the rare occasions you want to add some <script> exclusively for one page? You wouldn't be able to put it after footer.php because you wouldn't be in the <body> tag anymore, but you can't put it before, because then you'll be missing the jquery.js from your code.

Solution

Have a footer-start.php file:

<script src="jquery.js"></script>
<script src="custom.js"></script>

And a footer-end.php file:

</body>
</html>

And have your footer.php be simply:

<?php
  require 'footer-start.php';
  require 'footer-end.php';

Then, on the rare occasions that you need to use a custom <script> for one page, do this:

<?php require 'footer-start.php'; ?>
<script>...</script>
<?php require 'footer-end.php'; ?>

Doing it this way means you don't have to change all your previous code where footer.php is referenced.

Randell answered 30/5, 2015 at 14:56 Comment(0)
C
0

You should do it near </body>. The reason is simple: If you place it into the head area, the files must be loaded before the body area can be. For that time, the user just sees a white screen.

But it depends on your website. I would load frameworks like mootools in the head area, other functions for events or AJAX or something should be loaded near </body>.

Custom answered 18/6, 2009 at 14:55 Comment(1)
Re "near </body>": And before </body>. Otherwise it will not be valid HTML. HTML validation will result in "Error: Stray start tag script" (check option "source" and click "check" to see the HTML source). If it is before, it validates.Zitazitah
R
0

The only reason for putting it near the end of the body, AFAIK, is to be able to execute the JavaScript after the web browser has parsed your HTML document. E.g. if your JavaScript deals with "all elements named hello", the browser needs to read the entire document before executing your JavaScript. Makes sense, right?

In e.g. jQuery, you can put your JavaScript anywhere in your document and use:

$(document).ready(function () {
  // Your code here
});

...to make sure the entire document has been loaded into the DOM before executing the inner function. Of course, this can be done with normal JavaScript as well, but be careful not to break compatibility with some browsers, because their needs tend to differ a lot.

Ruler answered 18/6, 2009 at 14:56 Comment(2)
Does this mean..if I use Jquery for the most of my functionality then I can have my scripts at the bottom?? ThanksAegisthus
Yeah, basically, the ready handler works this way: if all the elements aren't loaded yet, it'll put your function in a queue and run it when the page is ready. If the page is ready (all elements are loaded), it'll run it right away.Chateau

© 2022 - 2024 — McMap. All rights reserved.