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


Javascript Problem Overview

Example from Googles +1 button:

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

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

Javascript Solutions

Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionusrView Question on Stackoverflow
Solution 1 - JavascriptJeremyView Answer on Stackoverflow
Solution 2 - JavascriptRobGView Answer on Stackoverflow
Solution 3 - JavascriptJames BillinghamView Answer on Stackoverflow
Solution 4 - JavascriptJimView Answer on Stackoverflow