Should I write script in the body or the head of the html? [duplicate]
Asked Answered
E

5

151

I have seen both ways, both implementation work just the structures are a bit different. In your experience, which work better and why?

Exceedingly answered 20/8, 2010 at 13:35 Comment(1)
See very good explanation and recommendation: https://mcmap.net/q/45045/-where-should-i-put-lt-script-gt-tags-in-html-markupSuggestion
S
112

I would answer this with multiple options actually, the some of which actually render in the body.

  • Place library script such as the jQuery library in the head section.
  • Place normal script in the head unless it becomes a performance/page load issue.
  • Place script associated with includes, within and at the end of that include. One example of this is .ascx user controls in asp.net pages - place the script at the end of that markup.
  • Place script that impacts the render of the page at the end of the body (before the body closure).
  • do NOT place script in the markup such as <input onclick="myfunction()"/> - better to put it in event handlers in your script body instead.
  • If you cannot decide, put it in the head until you have a reason not to such as page blocking issues.

Footnote: "When you need it and not prior" applies to the last item when page blocking (perceptual loading speed). The user's perception is their reality—if it is perceived to load faster, it does load faster (even though stuff might still be occurring in code).

EDIT: references:

Side note: IF you place script blocks within markup, it may effect layout in certain browsers by taking up space (ie7 and opera 9.2 are known to have this issue) so place them in a hidden div (use a css class like: .hide { display: none; visibility: hidden; } on the div)

Standards: Note that the standards allow placement of the script blocks virtually anywhere if that is in question: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/dtd.html and http://www.w3.org/TR/xhtml11/xhtml11_dtd.html

EDIT2: Note that whenever possible (always?) you should put the actual Javascript in external files and reference those - this does not change the pertinent sequence validity.

Sweettalk answered 20/8, 2010 at 13:57 Comment(8)
Do you have a source that have more information about this page blocking issue or how browser download resources?Exceedingly
@Exceedingly - the page render blocking is a commonly documented issue. Editing the answer to provide some other references as it depends somewhat on the environment (platform and browser/version)Sweettalk
Best answer on this topic so far, helpful! +1.Warlock
Regarding "do NOT place script in the markup such as <input onclick="myfunction()"/>", rare cases you might have to. Such as in img tag: onerrorLizalizabeth
@Lizalizabeth $().on("error", function(){}); is one example or if you want to avoid multiple errors (on the backup image) try $().one("error", function(){}); with the one function - jQuery specific but you can reverse the source if you want pure JavaScriptSweettalk
Great tip. No more inline event-handler attributes for me :)Rugose
About "Note that whenever possible (always?) you should put the actual Javascript in external files and reference those": it is not "always" possible, since the server-side processing language may be writing some parts of the JavaScript language when the page is built-up. A typical example is the "PHP2JS" variable declaration: var myvar = <?php echo $myvar ?>; So simple when done in the hosting page, isn't it?Bixler
@FabienHaddadi - that is a totally separate issue of how to get values from the host to the client page which you illustrate one example of.Sweettalk
L
43

The problem with writing scripts at the head of a page is blocking. The browser must stop processing the page until the script is download, parsed and executed. The reason for this is pretty clear, these scripts might insert more into the page changing the result of the rendering, they also may remove things that dont need to be rendered, etc.

Some of the more modern browsers violate this rule by not blocking on the downloading the scripts (ie8 was the first) but overall the download isn't the majority of the time spent blocking.

Check out Even Faster Websites, I just finished reading it and it goes over all of the fast ways to get scripts onto a page, Including putting scripts at the bottom of the page to allow rendering to complete (better UX).

Lyre answered 20/8, 2010 at 13:43 Comment(9)
Good answer, technically putting scripts in the header is clean, but from an end user point of view and SEO putting scripts right at the bottom of the document as the very last thing has many, many benefits. On some pages I've seen the apparent responsiveness of the page increase many fold just by moving the script to the bottom. Overall it may not fully load any faster, but to the end user as they see content it feels faster!Lucienlucienne
This seem rather true, I have problem delay my script execution until all of my resources have been loaded. And I have seen page that have scripts loaded inside body, that load resources so effectively. Could you explain this more clearly?Exceedingly
The specification says to block? Is that true? I believe they block for rendering reasons and not because any spec says to do so!Flashback
@Flashback I remember the book saying something about it, let me read over the spec and make sure (ill make edits if needed).Lyre
@Flashback can't find the word blocking in the html spec, it does mention the stopping of rendering (and the explanation of the script inserting html) but doesn't specifically say blocking, ill make edits.Lyre
@Exceedingly I don't really know what you mean by more clearly. Anything specific? What do you mean "all resources"? The script will executed in order as the pages loads, it doesn't wait unless you use callbacks triggerd by attributes like onload.Lyre
actually I fully get your point just now. I mean like image files and sound files sometime doesn't load on time or doesn't load at all. And using events such as onload/onready doesn't help. I have seen pages with scripts mostly stay in the body, that doesn't employ any special method, but still load all of the page's resources perfectly on time.Exceedingly
Are there any benchmarks comparing javascript in the head section verses just before the close body tag section? It has always felt like a bit of an old wife's tale. surely the browser has to download the whole html document before it can either parse the head or body? why would modern browsers process a page synchronously? i.e stop parsing the html just because it encounters some script.Orsa
gawpertron: The downloading is done asynchrnously in modern browsers starting with ie8 (according to even fast websites by steve souders). The requirement of executing before continuing parsing comes from the fact that scripts can dramatically change the structure of the dom. For example, they can use document.write and emit parts of a document immediately and you might even have scripts that are dependent on those side effects (see this example and imagine them being external scripts jsfiddle.net/struys/pZwQw).Lyre
S
11

W3Schools have a nice article on this subject.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in functions.

Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.

Skite answered 20/8, 2010 at 13:40 Comment(1)
What nonsense...Uracil
E
4

Head, or before closure of body tag. When DOM loads JS is then executed, that is exactly what jQuery document.ready does.

Evaporite answered 20/8, 2010 at 13:38 Comment(0)
S
1

I always put my scripts in the header. My reasons:

  1. I like to separate code and (static) text
  2. I usually load my script from external sources
  3. The same script is used from several pages, so it feels like an include file (which also goes in the header)
Solita answered 20/8, 2010 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.