2

Where is it legal to put a <script> tag in html?

I have a legitimate (I swear!) reason to use document.write in parts of my page. This means I need to put

<script>document.write('some goodness')</script>

at some arbitrary point in the DOM. Is that always supported?

4

2 回答 2

3

In HTML5 the <script> element is defined as being allowed in the following places:

Contexts in which this element can be used:

  • Where metadata content is expected.
  • Where phrasing content is expected.
  • Where script-supporting elements are expected.

Most content elements allow for phrasing content, and the <head> element allows for metadata content.

There are some elements that do not support the <script> element as direct descendants , and it should be noted that this list is subject to change, so consult the spec, as this is probably not a comprehensive list:

  • <html>
  • <title>
  • <script>

Additionally, you shouldn't put a <script> element in a <noscript> element because it simply doesn't make any sense to do so, even though it would technically be supported by the specification.

于 2013-11-14T18:41:18.747 回答
2

您可以将它们包含在您的<head>or<body>标记之间的任何位置:

  • 如果你在头部插入,它会在页面渲染之前加载,
  • 如果将它放在正文上,它将在所有页面呈现后加载,因此用户不会在页面呈现之前等待您的脚本被解析 =更快的页面呈现

例外:

  • <title>标签内(如你所说)
  • 里面<tr>见这个链接显然它确实(见后)

我在那个小提琴上尝试了一些元素,你可以试试

于 2013-11-14T18:32:40.503 回答