我应该在脚本的主体还是html的头部写脚本? [英] Should I write script in the body or the head of the html?

查看:157
本文介绍了我应该在脚本的主体还是html的头部写脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了两种方式,两种实现工作只是结构有些不同。在你的经验中,哪些工作更好,为什么?

解决方案

我会用多个选项实际回答这个问题, 。
$ b


  • 将库脚本(如jQuery库)放在头部分中。

  • 将正常脚本放在首位,除非它成为性能/页面加载问题。

  • 将与include关联的脚本放置在include和end内部。其中一个例子是asp.net页面中的.ascx用户控件 - 将脚本放在该标记的末尾。

  • 将影响页面呈现的脚本放置在body (在body关闭之前)。
  • 不要将脚本放在标记中,例如< input onclick =myfunction()/> - 最好将它放入脚本主体中的事件处理程序中。

  • 如果您无法做出决定,请将其置于首位,直到您有理由不阻止页面阻止问题。



脚注:当你需要它而不是先前时,适用于页面阻塞(感知加载速度)用户的感觉是真实的,如果它被加载的速度更快,它的加载速度会更快(即使代码中可能还有东西)。编辑:引用:



注意:如果您将脚本块置于标记内,它可能会影响某些浏览器的布局占据空间(ie7和歌剧9.2已知有这个问题),所以把他们放在一个隐藏的div(使用一个CSS类,如: .hide {display:none;知名度:隐藏;标准:请注意,如果有问题,标准允许在任何地方放置脚本块: http://www.w3.org/TR/1999/REC- html401-19991224 / sgml / dtd.html http://www.w3 .org / TR / xhtml11 / xhtml11_dtd.html



编辑2:请注意,只要有可能(总是?),您应该将实际的Javascript放入外部文件和参考那些 - 这不会改变相关的序列有效性。


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

解决方案

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 users perception IS thier reality, if it is percieved to load faster, it does load faster (even though stuff might still be occuring 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.

这篇关于我应该在脚本的主体还是html的头部写脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆