javascript 带有 src AND 内容的脚本标签是什么意思?

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

What does a script-Tag with src AND content mean?

javascript

提问by usr

Example from Googles +1 button:

来自 Google +1 按钮的示例:

<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
      {"parsetags": "explicit"}
</script>

The script Tag has a src-Attribute andcontent. What does this mean and how does it work?

脚本标签具有 src-Attribute内容。这是什么意思,它是如何工作的?

采纳答案by Facebook Staff are Complicit

Different browsers treat this differently. Some run the content only if the srcis included without error. Some run it after attempting to include the srcscript, regardless of success. Since this behaviour is unreliable (and prohibited in HTML5), it should be avoided.

不同的浏览器对此有不同的处理方式。有些仅在src包含无错误时才运行内容。有些人在尝试包含src脚本后运行它,无论成功与否。由于这种行为不可靠(并且在 HTML5 中禁止),因此应该避免。

Google isn't relying an any specific behaviour. Since the content is just an object literal (a value), executing it would not actually do anything except cause a silent error. Google's code looks at the contents of the scripttag itself, and adjust its behaviour based on that.

Google 不依赖任何特定行为。由于内容只是一个对象字面量(一个值),执行它实际上不会做任何事情,除了会导致静默错误。Google 的代码会查看script标签本身的内容,并根据这些内容调整其行为。

回答by RobG

If a script elementhas a srcattribute, the content mustbe ignored, any other behaviour is non-conformant.

如果脚本元素具有src属性,则必须忽略该内容,任何其他行为都是不一致的。

It has been suggested in blogs (as a hack) to put content in the element knowing that it won't be evaluated, then use DOM methods to get the content as a string and either evalit or insert it in a new script element. Neither of these are a good idea.

已经在博客中建议(作为 hack)将内容放入元素中,知道它不会被评估,然后使用 DOM 方法将内容作为字符串获取,并对其进行评估或将其插入新的脚本元素中。这两个都不是一个好主意。

回答by Jim

According to the HTML5 draft specification, <script>elements with srcattributes should only have commented-out code, which is intended to give documentation for the script. It doesn't appear as though Google is conforming to this specification though.

根据HTML5 草案规范<script>具有src属性的元素应该只具有注释掉的代码,旨在为脚本提供文档。不过,似乎 Google 并不符合此规范。

回答by James Billingham

After the script has loaded, it looks inside its own script tag to access its content.

脚本加载后,它会查看自己的脚本标签以访问其内容。

It will use some code similar to this:

它将使用一些类似于此的代码:

var scripts = document.getElementsByTagName("script");
var data = eval(scripts[scripts.length - 1].innerHTML);

Courtesy of John Resig.

John Resig 提供