有什么办法,除了使用eval / handleAs:“javascript”动态获取脚本(通过XMLHttpRequest) [英] Is there any way, other than to use eval/handleAs: "javascript" to dynamically fetch scripts (via XMLHttpRequest)

查看:154
本文介绍了有什么办法,除了使用eval / handleAs:“javascript”动态获取脚本(通过XMLHttpRequest)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处当我通过XMLHttpRequest动态加载脚本(换句话说,通过 eval )执行时,我提出了一个有关异常的问题。

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

在相关的问题中,我想知道是否将脚本动态加载,被认为是不好的做法。在我特定的情况下,我有一个HTML Canvas元素,而不是加载所有可能的形状,我想动态地抓取它们,而不重新加载页面,并在返回时执行它们。我遇到的问题是,如果与该形状相关联的代码不正确,则显示的错误消息不是很有用(表示 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.

推荐答案

如果要加载脚本,请使用< script> 元素。如果要动态加载脚本,请动态创建< script> 元素。

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);

不能保证以同样的方式 eval 同步XHR是,但理想情况下,您将构建您的代码以利用asynchony。

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.

这篇关于有什么办法,除了使用eval / handleAs:“javascript”动态获取脚本(通过XMLHttpRequest)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆