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?
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.
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.
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.
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.