将 JavaScript 嵌入到 HTML 正文中是不好的做法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2837921/
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 02:07:20  来源:igfitidea点击:

Is it bad practice to embed JavaScript into the body of HTML?

javascripthtml

提问by Andrew

A team that I am working on has gotten into the habit of using <script>tags in random places in the body of our HTML pages. For example:

我工作的一个团队已经养成了<script>在 HTML 页面正文中随机位置使用标签的习惯。例如:

<html>
    <head></head>
    <body>
        <div id="some-div">
            <script type="text/javascript">//some javascript here</script>
        </div>
    </body>
</html>

I had not seen this before. It seems to work in the few browsers that I've tested. But as far as I know, it's not valid to put script tags in places like this.

我以前没有见过这个。它似乎适用于我测试过的少数浏览器。但据我所知,将脚本标签放在这样的地方是无效的。

Am I wrong? How bad is it that we are putting script tags within div tags like this? Are there any browser compatibility issues I should be aware of?

我错了吗?我们将脚本标签放在这样的 div 标签中有多糟糕?是否有任何我应该注意的浏览器兼容性问题?

回答by bobince

It's perfectly valid.

这是完全有效的。

You wouldn't want to put great big blocks of code mixed up in the markup there (better to use external scripts), but it can be useful to:

您不希望将大量代码混合在那里的标记中(最好使用外部脚本),但它可以用于:

  • add extra binding information for progressive-enhancement (where that data is difficult to fit into a classname or other approach to hiding extended information in attributes); or

  • where it's necessary to kick off a scripted enhancement as quickly as possible (rather than waiting for window-load/document-ready). An example of this would be autofocus, which can irritate if fired too late.

  • 为渐进增强添加额外的绑定信息(该数据难以放入类名或其他隐藏属性中扩展信息的方法);或者

  • 有必要尽快启动脚本增强功能(而不是等待窗口加载/文档就绪)。这方面的一个例子是自动对焦,如果发射太晚会刺激。

You may be thinking of <style>elements, which aren't allowed in <body>(although most browsers allow it nonetheless).

您可能正在考虑<style>不允许进入的元素<body>(尽管大多数浏览器仍然允许)。

回答by Keltex

Actually, it's quite common. For example Google's analytics tracking codeuses just this syntax:

其实,这是很常见的。例如,Google 的分析跟踪代码仅使用以下语法:

<script type="text/javascript">
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>

If it's good enough for Google...

如果它对谷歌来说足够好......

回答by Pointy

It is valid and, depending on your server-side framework and the nature of the code, sometimes very difficult to avoid.

它是有效的,并且取决于您的服务器端框架和代码的性质,有时很难避免。

回答by Gal

As several people mentioned, it's valid, it works, and it is widely used.

正如一些人提到的,它是有效的、有效的并且被广泛使用。

Best practices as far as semantics recommend (or at least used to recommend) is placing script tags inside of the header.

就语义推荐(或至少用于推荐)而言,最佳实践是将脚本标签放置在标头内。

More modern best practices which take performance into account recommend placing script tags (external and inline) at the bottom right before the body tag, to allow the markup to render completely before any JavaScript code executes.

考虑到性能的更现代的最佳实践建议将脚本标签(外部和内联)放置在 body 标签前的右下方,以允许标记在任何 JavaScript 代码执行之前完全呈现。

For easier to understand and maintainable code, "unobtrusive JavaScript" is recommended, where the code is in an external file and binds events to the DOM (Google unobtrusive JavaScript).

为了更易于理解和维护代码,建议使用“unobtrusive JavaScript”,其中代码位于外部文件中并将事件绑定到 DOM(Google unobtrusive JavaScript)。

One case where it's useful to have JavaScript inline is to initialize variables with values that only exists server side, which will then later be used by the external JavaScript code.

内联 JavaScript 很有用的一种情况是使用仅存在于服务器端的值初始化变量,然后外部 JavaScript 代码将使用这些值。

回答by meo

It is valid!

这是有效的!

You can use:

您可以使用:

<script type="text/javascript">
    //<![CDATA[

    // Some JavaScript code that perfectly validates in the W3C validator

    //]]>
</script>

I don't think you can say if it is a bad practice in general. You have to tell in the case. But sure is that it is good to have all your JavaScript code at the same place. It's a little messy if you have little pieces of JavaScript code all over your HTML file.

我认为你不能说这是否是一种不好的做法。你必须在这种情况下告诉。但可以肯定的是,将所有 JavaScript 代码放在同一个地方是件好事。如果您的 HTML 文件中到处都是 JavaScript 代码片段,这会有点混乱。

回答by Matti Virkkunen

I prefer to put references to external scripts into the head, and scripts that start things up and initialize widgets and whatnot into the body.

我更喜欢将外部脚本的引用放入 head 中,并将启动和初始化小部件的脚本放入 body 中。

An issue that's very easy to run into is that a script element in the body cannot access elements that come after it. Also, a related nasty browser compatibility issue is the fact that IE doesn't allow script elements to modify the element they're in. So if you have this:

一个很容易遇到的问题是正文中的脚本元素无法访问它之后的元素。此外,一个相关的令人讨厌的浏览器兼容性问题是 IE 不允许脚本元素修改它们所在的元素。所以如果你有这个:

<div id="foo">
  <script type="text/javascript">
    document.getElementById("foo")... // do something to it
  </script>
</div>

IE is not going to like your page. Old versions of IE used to give very cryptic error messages for this or even blank the entire page, but IE8 seems to give a descriptive error message.

IE 不会喜欢你的页面。旧版本的 IE 过去常常为此给出非常神秘的错误消息,甚至整个页面都为空白,但 IE8 似乎给出了描述性的错误消息。

As long as you make sure that your scripts only access DOM that's safe to access, I don't think it's evil to put script elements into the body. In fact, IMHO, putting scripts that initialize widgets after the related elements can be more readable than putting everything in one place (and I believe this might also make them run earlier, which makes stuff jump around less as the page loads).

只要您确保您的脚本只访问可安全访问的 DOM,我认为将脚本元素放入正文中并不是一件坏事。事实上,恕我直言,在相关元素之后放置初始化小部件的脚本比将所有内容放在一个地方更具可读性(我相信这也可能使它们运行得更早,这使得页面加载时跳转的内容更少)。

回答by Will Hartung

However, it's also good in that you know the JavaScript code needed for a section of HTML is going to be there for it. Rather than having to assert and build up some inclusion at the top of the file.

然而,这也很好,因为您知道一段 HTML 所需的 JavaScript 代码将在那里。而不是必须在文件顶部断言和建立一些包含。

So, rather than "if you're going to use this HTML, make sure you import xyz.js" you can just include the HTML and be done with it.

因此,与其“如果您要使用此 HTML,请确保导入 xyz.js”,您可以只包含 HTML 并完成它。

So, it's not necessarily horrible evil. Perhaps not spectacularly awesome, but not utterly terrible either. It kind of depends on the intent.

所以,它不一定是可怕的邪恶。也许不是特别棒,但也不是完全可怕。这有点取决于意图。

回答by Jonathan Lebrun

See the Yahoo UI for best practice: http://developer.yahoo.com/performance/rules.html(JavaScript at the bottom of the page)

有关最佳实践,请参阅 Yahoo UI:http: //developer.yahoo.com/performance/rules.html(页面底部的 JavaScript)

回答by Jonathan Lebrun

I had not seen this before. It seems to work in the few browsers that I've tested. But as far as I know, it's not valid to put script tags in places like this.

我以前没有见过这个。它似乎适用于我测试过的少数浏览器。但据我所知,将脚本标签放在这样的地方是无效的。

It's valid, but not a good (or recommended) practice.

这是有效的,但不是一个好的(或推荐的)做法。

Am I wrong? How bad is it that we are putting script tags within div tags like this? Are there any browser compatibility issues I should be aware of?

我错了吗?我们将脚本标签放在这样的 div 标签中有多糟糕?是否有任何我应该注意的浏览器兼容性问题?

There's no problem placing a <script>under any other elements (but it should be inside <head>or <body>). There's also no issue in terms of browser compatibility, however, embedding JS scripts on web pages presents serious disadvantages (how/why they are considered bad):

将 a<script>放在任何其他元素下没有问题(但它应该在<head>或 内<body>)。在浏览器兼容性方面也没有问题,但是,在网页上嵌入 JS 脚本存在严重的缺点(它们如何/为什么被认为是不好的)

  1. Adds page weight
  2. Difficulty (or probably impossible) for minification
  3. Cannot be migrated or be used for other pages
  4. Cannot be cached (needs to be downloaded every time the page is loaded)
  5. No separation of concerns (harder to maintain)
  1. 添加页面权重
  2. 缩小的难度(或可能不可能)
  3. 无法迁移或用于其他页面
  4. 无法缓存(每次页面加载都需要下载)
  5. 没有关注点分离(更难维护)

回答by ChrisF

It's certainly legal; I've seen it on a few pages here on Exforsysfor example.

这当然是合法的;例如,我在 Exforsys上的几页看到过它。

Now this is a tutorial site showing the basics of HTML and JavaScript so in that context it's perfectly understandable. However, I wouldn't like to see it in production code for anything more than a simple statement or two. Without seeing what you've replaced by // Some JavaScript code hereI wouldn't like to comment.

现在这是一个教程站点,展示了 HTML 和 JavaScript 的基础知识,因此在这种情况下它是完全可以理解的。但是,除了一两个简单的语句之外,我不希望在生产代码中看到它。没有看到你替换了什么,// Some JavaScript code here我不想发表评论。

There shouldn't be any browser issues with this though.

不过,这不应该有任何浏览器问题。