Script tag with both external source and body

前端 未结 3 876
日久生厌
日久生厌 2020-12-03 22:18

I just came across this sample code, which has a script tag with both an external source and a body. I assume that this is a clever way to pass some information to the inclu

相关标签:
3条回答
  • 2020-12-03 22:54

    Although browsers are said to ignore the contents of a script element when it has a src attribute, this just means that they don’t process it the normal way (parse and run as JavaScript code). The contents are still stored in the DOM and can be read by a script. The contents could be just about anything then, not necessarily JavaScript code but any data.

    0 讨论(0)
  • 2020-12-03 22:57

    The script contained in the tags will not be evaluated under normal circumstances. What I think is happening in your example is that remoteStorage.js is reading the contents itself as it is evaluated. something like this

    //grab the last script tag in the DOM
    //this will always be the one that is currently evaluating during load
    var tags = document.getElementsByTagName('script');
    var tag = tags[tags.length -1];
    //force evaluation of the contents
    eval( tag.innerHTML );
    

    Although this looks neat in the markup, I, myself would just use a separate script tag and avoid this forced evaluation.

    0 讨论(0)
  • 2020-12-03 23:13

    It shouldn't work. The html specs state that if there's a src attribute on the script tag, the contents of the <script></script> should be ignored and only the code at the src location should be executed.

    On the other hand, this would gracefully degrade on browsers that understand javascript, but are not new enough to support external JS code. If any browsers like this exist, who knows, but generally speaking, the onchange code in your snippet should NOT be executed by any decent modern browser.

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