Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I found that sometimes the script don't run properly when I add script tag in the head section. But when I add script right before the ending tag of body it works fine.

What is the difference between adding script in head tag
on just before ending body tag
right after the control?

I found this issue very often when I use JQuery..

share|improve this question

closed as not a real question by Yannis Jun 15 '12 at 6:09

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

Although Jalayn's answer is the most likely cause, we can't really speculate what's wrong with your scripts unless you show us your actual code. If you decide to do so, please post the question on Stack Overflow, technical questions are off topic for Programmers. – Yannis Jun 15 '12 at 6:09
Why was this closed? – Oliver Weiler Jun 15 '12 at 8:10
@OliverWeiler Because it's off-topic. – FishBasketGordo Jun 15 '12 at 11:40
up vote 4 down vote accepted

It is very simple in fact. If your script is not bound to a document ready event, it will fire up instantly, that is, when the page is being loaded, NOT when it has loaded. What it means is that the HTML controls/tags below your script tag have not been added yet to the DOM. And as such, attempting to interact with them will not work.

If you place your script tags after the control/tag is created, the tag is in the DOM and jquery "sees" it.

For these reasons it is always recommended to bind your javascript to a document "ready" function, so that it will fire only when the DOM tree has been properly and completely instantiated.

For a more detailed explanation, you might be interested in reading this post, about the "ready" function.

Also, check out if you are interested in knowing how the web page is loaded by the browser (hint: top to bottom, or "as it is seen"). The advice in the top answer is to place the script tag at the end of the document, which makes sense, but if you are using jquery, whatever the place of your script tag is, if you wrap your code in a "ready" function you won't have any problems.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.