Javascript JS 脚本应该放在 HTML 文件中的什么位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5220313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:13:03  来源:igfitidea点击:

Where should JS scripts go in an HTML file?

javascripthtml

提问by Mr. Boy

If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go? For instance modifying a <div>or adding some links. Should this be put in the <body>, interspersed with HTML? Or should it be betweenthe <head>and <body>elements? What order do things happen in - the order they are in the page or does HTML all happen before (non-<head>) JS is run?

如果您的 JS 代码旨在作为加载/构建页面的一部分运行,那么这应该放在 HTML 中的哪个位置?例如修改一个<div>或添加一些链接。这应该放在<body>, 穿插 HTML 吗?还是应该在和元素之间?事情发生的顺序是什么 - 它们在页面中的顺序还是 HTML 是否在(非)JS 运行之前发生?<head><body><head>

采纳答案by hennes

The whole HTML file is executed in the order it is written, that means

整个 HTML 文件按照编写的顺序执行,这意味着

<html>
  <div id="ID"></div>
  <script type="text/javascript">
    document.getElementById('ID').innerHTML = "HELLO";
  </script>
</html>

changes the contents of the div, wherease

更改 div 的内容,而

<html>
  <script type="text/javascript">
    document.getElementById('ID').innerHTML = "HELLO";
  </script>
  <div id="ID"></div>
</html>

does not, because the JS code is executed before the div has loaded.

不会,因为 JS 代码是在 div 加载之前执行的。

EDIT: If you want the JS to run after the page has loaded use window.onload or document.body.onload or

编辑:如果您希望 JS 在页面加载后运行,请使用 window.onload 或 document.body.onload 或

<body onload="...">

Alternatively if you're using a JS library such as jQuery, you can use

或者,如果您使用的是 JS 库,例如 jQuery,则可以使用

$(document).ready(function() {
  ...
});

回答by T.J. Crowder

If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go?

如果您的 JS 代码旨在作为加载/构建页面的一部分运行,那么这应该放在 HTML 中的哪个位置?

Just before the closing </body>tag is emerging as the best practice barring a specific requirement for it to be elsewhere (which there can sometimes be). It's the recommendation of the YUI folks, for instance, but it's not just them.

就在结束</body>标记作为最佳实践出现之前,除非特定要求将其置于其他地方(有时可能存在)。例如,这是YUI 人员推荐,但不仅仅是他们。

What order do things happen in - the order they are in the page or does HTML all happen before (non-) JS is run?

事情发生的顺序是什么 - 它们在页面中的顺序还是 HTML 是否在(非)JS 运行之前发生?

When a scripttag is encountered, unless you use the deferor asyncattribute(and the browser supports them), all HTML parsing comes to a screeching halt and the script is downloaded and handed to the JavaScript interpreter. When the JavaScript interpreter finishes processing the script, the HTML parser can continue. It has to do this because the JavaScript can insert tokens into the HTML stream via document.write. This is also why you can load a script file and then load a second script file that relies on the first, and know that they'll get loaded in the right order. It's alsowhy you can't access elements that are further down in the HTML stream from a script higher up in it unless you defer your code somehow (window.onloador the "DOM loaded" events many libraries support, such as jQuery's readyor Prototype's dom:loaded).

script遇到标签时,除非您使用deferorasync属性(并且浏览器支持它们),否则所有 HTML 解析都会突然停止,脚本会被下载并交给 JavaScript 解释器。当 JavaScript 解释器完成对脚本的处理后,HTML 解析器可以继续。它必须这样做,因为 JavaScript 可以通过document.write. 这也是为什么您可以加载一个脚本文件,然后加载依赖于第一个脚本文件的第二个脚本文件,并且知道它们将按正确的顺序加载。这也是为什么你不能从更高的脚本访问 HTML 流中更深的元素的原因,除非你以某种方式推迟你的代码(window.onload或许多库支持的“DOM 加载”事件,例如 jQueryready或 Prototype 的dom:loaded)。

An upshot of this is that the typical practice of putting scripttags in the headactually slows down the apparent load time of the page, unless those scripttags needto be there for some reason. Hence the recommendation to put them just before the closing </body>tag.

这样做的一个结果是,将script标签放入的典型做法head实际上会减慢页面的明显加载时间,除非出于某种原因需要这些script标签。因此建议将它们放在结束标记之前。</body>

There's a "gotcha" you have to watch for, though: If you have parts of the page that you want to respond to with JavaScript if the user has it enabled, loading your script at the very end leaves a brief but real race condition lying around: The user can interact with the page while your script is being downloaded. There are a variety of ways of handling that. My favorite is to detect whether JavaScript is enabled with inlinescript (not a separate file) in the headelement and, if so, to put in a document-level handler for things where possible (you can do this with clickevents, for instance) which basically queues up or disables the click during that very brief period of time. That way, if JavaScript is enabled, you'll avoid the race condition, but if it isn't, any unobtrusivefallback you have in place will work.

但是,您必须注意一个“问题”:如果您希望在用户启用 JavaScript 的情况下使用 JavaScript 响应页面的某些部分,那么在最后加载您的脚本会留下一个简短但真实的竞争条件周围:用户可以在下载脚本时与页面进行交互。有多种处理方法。我最喜欢的是检测元素中的内联脚本(不是单独的文件)是否启用了 JavaScript head,如果是,则在可能的情况下放入文档级处理程序(例如,您可以使用click事件执行此操作)基本上是在很短的时间内排队或禁用点击。这样,如果启用了 JavaScript,您将避免竞争条件,但如果不是,你的后备将起作用。

回答by BalusC

Put them as functions in its own .jsfile which you include by <script src>at end of HTML <head>or <body>. If any of them needs to be executed during document load, call it using window.onloador whatever load function the JS library/framework offers, if you are using any.

将它们作为函数放在自己的.js文件中,您可以<script src>在 HTML<head><body>. 如果需要在文档加载期间执行其中任何一个,请使用window.onload或 JS 库/框架提供的任何加载函数调用它(如果您正在使用任何函数)。

As to the exact location, putting them in end of <head>allows them to be downloaded before the HTML page is been shown in browser and putting them in end of <body>allows the page to be shown a tad sooner because downloading the scripts will block the page rendering, thus it's a better speed experience.

至于确切的位置,将它们放在末尾<head>允许在 HTML 页面在浏览器中显示之前下载它们,将它们放在末尾<body>允许页面更快显示,因为下载脚本会阻止页面渲染,因此它是一个更好的速度体验。

However, IMO, it's a bit more robust to have the scripts downloaded before the page is rendered whenever you have some page elements which cannotbe used without JS. In case of an impatient user this would otherwise lead to unusable elements.

但是,IMO,只要您有一些没有 JS就无法使用的页面元素,那么在呈现页面之前下载脚本会更加健壮。如果用户不耐烦,这将导致无法使用的元素。

回答by Wukerplank

I'd put it in a separate .jsfile and wrap the code so it is executed after the DOM is loaded. If you use a framework like jQuery or Prototype this should be easy.

我将它放在一个单独的.js文件中并包装代码,以便在加载 DOM 后执行它。如果您使用像 jQuery 或 Prototype 这样的框架,这应该很容易。

回答by Josh K

For best performance place your JavaScript files at the BOTTOM of the HTML page you are serving.

为获得最佳性能,请将您的 JavaScript 文件放在您所服务的 HTML 页面的底部。

To ensure that everything is set when you try to use it, execute only after the DOM is ready (there are multiple variations of this, my advice: Use a JavaScript Library).

为了确保在您尝试使用它时一切都已设置,请仅在 DOM 准备就绪后执行(这有多种变体,我的建议是:使用 JavaScript 库)。

回答by Josh K

You can put a script tag in the head, body, between the two, and more. You can put it most places but see thisfor a more in depth look.

您可以在头部、主体、两者之间等位置放置脚本标记。您可以将它放在大多数地方,但请查看此内容以获得更深入的了解。