What's the Difference Between Putting Script in Head and Body

is there a difference between putting a javascript in the head or in the body?

It is always better to put javascript at the bottom just before </body>. That way it doesn't block rendering (good for performance). Also, at that point you know the DOM (the tree of HTML elements) is ready for you.

$(document).ready(function () {}) is jQuery's way of waiting until the DOM is ready. If you put your javascript in the <head> you have to use this technique, because obviously all the actual HTML you want to work with comes after it and needs to be parsed. The callback (the function passed to .ready()) gets called once the DOM is ready.

Should I write script in the body or the head of the html?

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:

  • asp.net discussion: http://west-wind.com/weblog/posts/154797.aspx
    and here: http://msdn.microsoft.com/en-us/library/3hc29e2a.aspx
  • jQuery document ready discussion: http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/?utm_source=feedburner&utm_medium=email&utm_campaign=Feed%3A+Encosia+%28Encosia%29
  • the other answers on this question present valid information as well.
  • use www.google.com and www.bing.com to search for related information (there are a lot of 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.

What's the difference between HTML head and body tags?

Generally javascript code will function in the head before code in the body. The head section is usually used to contain information about the page that you dont neccessarily see like the meta keywords meta description or title of a page. You would also link to any external files like .css .js files in the head section as they need to load before the page is displayed.

Anything in the body section is what you would expect to be see on screen.

What's Pros and Cons: putting javascript in head and putting just before the body close

From Yahoo's Best Practices for Speeding Up Your Web Site:

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.

Therefore, in general, it is preferrable to put them at the bottom. However, it isn't always possible, and it often doesn't make that much of a difference anyway.

What is the difference when including script tag in HTML's header or body

Most of the time you want to include scripts at the bottom of the body section. The basic reason is to ensure that the page (and consequently the DOM) has fully loaded before any javascript is executed upon it.

Additionally, since downloading scripts blocks the browser from downloading anything else at the same time, the page will appear to load faster if the page elements are loaded before the script. However, unless you are a huge website that gets lots of traffic like Yahoo or Google, you probably do not need to consider this.

Why my code doesn't work when the script tag is in the head tag?

First, the HTML get parsed from top to bottom, So Whatever encounter first will get run.

If you put script tag at the end of the head tag then It will run first before the HTML body so you can't set width because when you used

document.getElementById("video")

It would return null so you can't set properties on null. Because at the time of this statement the element doesn't exist.

<html>

<head>
<script>
const heading = document.querySelector("h1");
console.log(heading); // null
</script>
</head>

<body>
<h1> This is heading</h1>
</body>

</html>


Related Topics



Leave a reply



Submit