Script tags with src and code between script tags

前端 未结 4 1771
执念已碎
执念已碎 2020-12-06 19:16

Is the following valid javascript? Would the variable be available to the externally called script?



        
4条回答
  •  甜味超标
    2020-12-06 19:29

    No, it's not possible to do what you're doing directly. However there's a clever little hack you can employ to enable it: http://ejohn.org/blog/degrading-script-tags/

    Consider the following HTML snippet:

    
    

    Add the following code to the end of your external.js file:

    var scripts = document.getElementsByTagName("script");
    var length = scripts.length;
    var script = scripts[length - 1].innerHTML;
    eval(script);
    

    Note however that eval must be called indirectly so that the script is executed in the global scope.

提交回复
热议问题