Is there any way, other than to use eval/handleAs: “javascript” to dynamically fetch scripts (via XMLHttpRequest)

廉价感情. 提交于 2020-01-16 01:03:10

问题


Here I have asked a question pertaining to exceptions raised when dynamically loading scripts via XMLHttpRequest (in other words when executed via eval)

In a related question, I wanted to know whether loading scripts dynamically as such is considered bad practice to begin with. In my particular case I have an HTML Canvas element, and rather than load all possible shapes, I want to fetch them dynamically, without reloading the page, and execute them on return. The problem I am having there is that if the code associated with that shape is incorrect, the error message displayed is not very useful (indicates location of eval statement, not incorrect statement). Is there another way to dynamically fetch code from the server and execute it, while better informing the location of the exception when it occurs.


回答1:


If you want to load a script use a <script> element. If you want to dynamically load a script, create the <script> element dynamically.

var script = document.createElement('SCRIPT');
script.src = "<url to load>";
document.getElementsByTagName("HEAD")[0].appendChild(script);

It's not guaranteed to be synchronous the way eval with synchronous XHR is, but ideally you'd structure your code to take advantage of asynchony.




回答2:


Adding to Mike's answer, if you want good debugger support including a script tag is probably the way to go, since that is what debuggers are used to working on. The main differences from eval that you need to be aware of are:

  • Eval runs in the scope of where its called while included script tags run in the global scope.
  • Eval is synchronous while included tags run asynchronously. (You will need to use something like JSONP and dojo.io.script if you need to run code after the script tag finishes).

If the scripts are fixed you can also consider debugging them by including their script tags and deploying them as you see fit.



来源:https://stackoverflow.com/questions/7869957/is-there-any-way-other-than-to-use-eval-handleas-javascript-to-dynamically-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!