Does javascript have to be in the head tags?

后端 未结 11 651
逝去的感伤
逝去的感伤 2020-11-27 03:46

I believe javascript can be anywhere (almost), but I almost always see it in between . I am using jquery and wanted to know if it has

相关标签:
11条回答
  • 2020-11-27 04:07

    Just be careful about the bad effects on latency that you can have, depending on the user's browser and where exactly you place your Javascript in the page -- see just about all that Steve Souders has to say, including the videos of his Stanford lectures, and the fruit of his labors left behind e.g. here (put scripts at the bottom of the page in as much as feasible, etc etc).

    0 讨论(0)
  • 2020-11-27 04:09

    JavaScript is executed wherever it is found in the document. If you place inline JavaScript in the body, it will be executed when the browser comes to it. If you're using $(document).ready(...) to execute things, then the positioning shouldn't matter. Otherwise, you may find corner cases where it matters. In general, it does not matter. Scripts end up in the head tag mostly out of tradition.

    0 讨论(0)
  • 2020-11-27 04:12

    It can go in the head or body tag. Just keep in mind that it will execute whenever is read and not necessarily when the document is finished loading. Take a look here.

    0 讨论(0)
  • 2020-11-27 04:13
    1. Because you don't want JavaScript mixed with HTML - content with behaviour. Preferably you want it in a separate file.

    2. Having JS elsewhere has advantages and disadventages - it will be executed at different time, for instance, and you can write to the document from javascript located in the body.

    0 讨论(0)
  • 2020-11-27 04:13

    In some cases, yes the script may not work if its in the wrong location. Some JavaScript needs to be executed after a specific HTML element, others need to be exactly where you want your script output to show, others should be in the head of the document. It really depends on how the code is written. If you are not sure, you should execute your code on window.load or DOMready: http://www.javascriptkit.com/dhtmltutors/domready.shtml

    0 讨论(0)
  • 2020-11-27 04:21

    No, it can be anywhere. In fact, it’s sometimes a good idea to put it at the bottom of the document. For an explanation why, see http://developer.yahoo.com/performance/rules.html#js_bottom.

    0 讨论(0)
提交回复
热议问题