問題描述
帶有 src AND 內容的 script‑Tag 是什麼意思? (What does a script‑Tag with src AND content mean?)
Example from Googles +1 button:
<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
{"parsetags": "explicit"}
</script>
The script Tag has a src‑Attribute and content. What does this mean and how does it work?
‑‑‑‑‑
參考解法
方法 1:
Different browsers treat this differently. Some run the content only if the src
is included without error. Some run it after attempting to include the src
script, regardless of success. Since this behaviour is unreliable (and prohibited in HTML5), it should be avoided.
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 script
tag itself, and adjust its behaviour based on that.
方法 2:
If a script element has a src attribute, the content must be ignored, any other behaviour is non‑conformant.
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 eval it or insert it in a new script element. Neither of these are a good idea.
方法 3:
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.
方法 4:
According to the HTML5 draft specification, <script>
elements with src
attributes 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.
(by usr、Jeremy、RobG、James Billingham、Jim)