在 HTML 中包含 JavaScript 文件将不能作为 <script .... />

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

Include JavaScript file in HTML won't work as <script .... />

javascripthtml

提问by Freddie

I'd like to include a javascript file on every page of a site. I can do this with:

我想在网站的每个页面上都包含一个 javascript 文件。我可以这样做:

<script type="text/javascript" src="myFile.js" ></script>

This works fine - however as there's nothing between the two tags, I wanted to change it to:

这工作正常 - 但是由于两个标签之间没有任何内容,我想将其更改为:

<script type="text/javascript" src="myFile.js" />

If I do this, it doesn't work - nothing after that line loads on the page.

如果我这样做,它就不起作用 - 在页面上加载该行之后什么也没有。

Any ideas why? Thanks

任何想法为什么?谢谢

回答by Dekker500

Unfortunately, the HTML specs for REQUIRE a closing tag...

不幸的是,需要一个结束标记的 HTML 规范......

HTML Standard, section 18.2.1

HTML 标准,第 18.2.1 节

18.2.1 The SCRIPT element

Start tag: required, End tag: required

18.2.1 SCRIPT 元素

开始标签:必填,结束标签:必填

回答by Sean Patrick Floyd

This is not a bug, it's standard behavior.

这不是错误,而是标准行为。

Also, empty HTML elements are often not rendered:

此外,通常不会呈现空的 HTML 元素:

<div style="background:red"></div>displays, <div style="background:red" />doesn't

<div style="background:red"></div>显示,<div style="background:red" />

回答by david

HTMLdoesn't support self closing tags. If you want to use them you need to use an xml based doctype AND serve the file as xml.

HTML不支持自闭标签。如果你想使用它们,你需要使用基于 xml 的文档类型并将文件作为 xml 提供。

XHTML or the xml serialisation of html5 would both work.

XHTML 或 html5 的 xml 序列化都可以。

Here is an example:

下面是一个例子:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>XHTML5 Template</title>
    <meta charset="utf-8" />
    <script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js" />
  </head>
  <body>
  </body>
</html>

Save this in a file with a .xhtmlextension and open it in a modern browser and the self closing tag will work.

将其保存在一个带有.xhtml扩展名的文件中,并在现代浏览器中打开它,自关闭标签将起作用。