25

I see that Javascript code is normally in heading part of HTML code.

<head>
<script type="text/javascript" language="javascript" src="core.js"></script>
...
</head>

Is it OK to put the Javascript code in a body part of HTML code? I tested it, but it seems to work.

<body>
<script type="text/javascript" language="javascript" src="core.js"></script>
...
</body>

If so, why the examples of Javascript books put the javascript code in heading part? If not, what's the difference between putting the javascript code in body/heading part?

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
prosseek
  • 182,215
  • 215
  • 566
  • 871
  • This question does a good job of covering the topic: http://stackoverflow.com/questions/143486/unobtrusive-javascript-script-at-the-top-or-the-bottom-of-the-html-code – wsanville Dec 09 '10 at 14:10
  • I'd appreciate if someone would also mention what's the best practice for including Javascript which affects the page's looks heavily, in order not to let the user see the "half-rendered, not JS-processed" page during loading. – Kos Dec 09 '10 at 14:34
  • 2
    @Kos: Google for FOUC (flash of unstyled content) For what you are talking about, I would give those elements a visibility: hidden; style, have the styling execute on dom:ready, and remove that hidden style at the end of my event handler. – Matt Briggs Dec 09 '10 at 14:56

8 Answers8

18

Not only is it OK, it's actually better, since it lets the content come first.

If your viewers have a slow (eg, mobile) connection, it's better to send the actual content first, so that they can read it while the browser downloads the Javascript.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    totally fine with him accepting this answer over mine, but I really hope it isn't because he thinks SLaks is advocating sprinkling script tags all over the place – Matt Briggs Dec 10 '10 at 00:16
13

All the people saying it is better only applies if you are talking about at the bottom of the page (and that is an up for debate thing) from a code quality point of view, it is NOT ok to sprinkle script tags through your html. All references to javascript should be in a single place on the page, either the head (where they should be), or the very bottom (as a perf optimization)

Edit:

Basically, a web page is made up of 3 pieces; style (css), structure (html), and behavior (javascript). These pieces are all very distinct, so it makes sense to keep them as separate as possible. That way if you need to change some javascript, it is all in one place. If it is sprinkled through the file, it becomes much more difficult to find the code you are looking for, and that code basically becomes noise when you are just looking at structure.

It is the same arguments as why not sprinkle db access code all over your page. It has nothing to do with technical reasons, purely an architectural/design decision. Code that does different things should be kept separate for readability, maintainability, and by extension, refactorability (not sure if that last one is actually a word...)

Matt Briggs
  • 41,224
  • 16
  • 95
  • 126
3

You can do it, and people often do.

For example, people like to put their script tags just before the closing </body> to make web pages render quicker.

Also, if you do a script block after an element is created, you don't need to wait for DOM ready.

Be warned though, don't add, or remove an element from an unclosed ancestor in the markup tree (not including the script block's immediate parent element), or you will get the dreaded Operation Aborted error in IE.

alex
  • 479,566
  • 201
  • 878
  • 984
3

Just something to add on:

I have preference of putting Javascript file right before </body>. My reasons being that:

  • Content can load and be shown first. If you load huge Javascript files first, which most are meaningless until the page is loaded, the user won't be able to see anything until the JS files are loaded.
  • Most Javascript code require to work with the UI can only run after the UI has been loaded. Placing the codes at the end of the html file reduces the need to use the onload event handler.
  • It is very bad habit to place Javascript snippets all over the HTML file. Placing all at the back of the HTML file allows you to manage your Javascript more efficiently.
mauris
  • 42,982
  • 15
  • 99
  • 131
1

It is legal according to the spec.

Most examples use them in the header as the headers come first and the browser will be able to parse the reference and download the JS files faster.

Additionally, these are links and are not part of the display, so traditionally, put in the header.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

It is perfectly legal but there seem to be some differing opinions about it. Those who say to put all the javascript references in the head argue that the script is downloaded before the rest of the page become visible and dependent on it. So your user will not see an object on screen, attempt to interact with it and get an error because the javascript code is not yet loaded.

On the other hand, the argument goes that it takes longer to load all the script before the user sees the page and that can have a negative impact on perceived speed of your site.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
  • @Vincent: However, if there are JavaScript errors when the user tries to interact with the page before the external scripts load, that means that the page author is using `onclick` et al, and should be LARTed. – cdhowie Dec 09 '10 at 14:16
  • @cdhowie true. I expect that you can avoid the errors that I mentioned, I am just pointing out the argument, not necessarily agreeing with it. – Vincent Ramdhanie Dec 09 '10 at 14:17
  • @vincent: He is referring to a different technique called unobtrusive javascript, which is the way you should be doing your event handling anyways. if you are seeing those errors, there are much better ways to handle events then you are currently using. – Matt Briggs Dec 09 '10 at 14:20
  • @Vincent: Understood. I'm just pointing out that for the argument to be valid, the page author must be doing something dumb. :) – cdhowie Dec 09 '10 at 14:20
  • @Matt Briggs. Thanks. I am not seeing those errors. I was just commenting on an argument that you see by some parties for putting javascript exclusively in the head. – Vincent Ramdhanie Dec 09 '10 at 14:26
  • @Vincent: Not trying to put you down or anything :) What I was trying to say is that argument becomes invalid when a person handles events the "right" way, not really you specifically. I remember talking about unobtrusive javascript on the IRC way back in 2000-2001, there is really no excuse nowadays not to know about it, so that argument should be dead. – Matt Briggs Dec 09 '10 at 14:52
1

JavaScripts inside body will be executed immediately while the page loads into the browser

Placing javascript at the end of the body will defer javascript load (ie: the page will render faster), but remember that any javascript function used for an event should be loaded before the event declaration, it is mainly because users may be able to fire an event before the page is completely loaded (so before the function is loaded)!

Opty
  • 504
  • 5
  • 10
  • Your event handling code shouldn't be in the html at all. Google for unobtrusive javascript, it makes event handling much cleaner, and that specific problem just goes away. – Matt Briggs Dec 09 '10 at 14:58
  • Completely agree with this excepted on old slow browsers, which are mostly still used in big companies, where adding lot of events is a mess – Opty Dec 09 '10 at 15:56
0

I used to put it in the head, then I've heard that it takes longer for the page to load so I started placing the scripts at the very bottom. However, I found out the most 'clean' way to do it is to place it in the head BUT you place the script inside a document.ready function. This way you have the best of both worlds. It is cleaner because it is in the head and it is not loaded before the content has been loaded, so there aren't any problems performance wise either.

With jQuery for instance, you can do it like this:

$(document).ready(function() {
    alert('test');
});

The alert will only popup when the page has been fully loaded, even though the script is in the head.

seedg
  • 21,692
  • 10
  • 42
  • 59