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

后端 未结 4 618
执笔经年
执笔经年 2020-11-22 06:42

Example from Googles +1 button:



        
相关标签:
4条回答
  • 2020-11-22 06:46

    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.

    0 讨论(0)
  • 2020-11-22 06:54

    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.

    0 讨论(0)
  • 2020-11-22 07:00

    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.

    0 讨论(0)
  • 2020-11-22 07:02

    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.

    0 讨论(0)
提交回复
热议问题