2

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
OR
on just before ending body tag
OR
right after the control?

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

3
  • 2
    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, 2012 at 6:09
  • 3
    Why was this closed? Jun 15, 2012 at 8:10
  • @OliverWeiler Because it's off-topic. Jun 15, 2012 at 11:40

1 Answer 1

5

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 https://stackoverflow.com/q/1307929/866172 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.

1
  • The plain javascript equivalent to jquery's "ready", is document.addEventListener("DOMContentLoaded", function(){...}); When using jquery, there is no reason not to use "ready" (indeed, it is able to fire slightly earlier in some circumstances - though probably not enough to be significant); just mentioning plain javascript so people are aware of that alternative. Oct 16, 2019 at 8:14

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