用于运行远程代码的 eval 的替代方案
是否有任何替代方法可以使用 eval
立即运行远程&可信的 JavaScript 代码。
function load(filePath) {
var o = $.ajax({
url: filePath,
dataType: 'html',
async: false
});
eval(o.responseText);
}
load("somePath");
// run a function that relies on the code from o.responseText being loaded
doSomethingWithCode();
我知道不建议同步加载 javascript。但如果别无选择,是否有任何跨浏览器替代方案可以使用上面的 eval。
[编辑]
更详细地阐明正在加载的代码是一个自执行函数。需要在 doSomethingWidthCode 之前执行。它也是从同一域上的服务器加载的,因此它是可信的。
Are there any alternatives to using eval
to immediatly run remote & trusted javascript code.
function load(filePath) {
var o = $.ajax({
url: filePath,
dataType: 'html',
async: false
});
eval(o.responseText);
}
load("somePath");
// run a function that relies on the code from o.responseText being loaded
doSomethingWithCode();
I'm aware that synchronous loading of javascript is adviced againts. But if there is no choice are there any cross browser alternatives for the use of eval above.
[Edit]
To clarify in more detail the code being loaded is a self executing function. Which needs to execute before doSomethingWidthCode. It's also being loaded from the server on the same domain hence its trusted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
动态脚本文本插入是
eval
的唯一替代方案。唯一需要提及的是:
textContent
在 InternetExplorers 中不可用。您需要使用.text
代替,因此对此进行一些检测即可使其跨浏览器兼容。编辑
要使
同步
加载动态脚本标记,您可以添加nscr.async = true;
。无论如何,这只适用于最先进的浏览器。Dynamic script text insertion is the only alternative to
eval
.Only thing to mention:
textContent
is not available in InternetExplorers. You would need to use.text
instead there, so a little detection for that makes it cross-browser compatible.edit
To have a
syncronous
loading dynamic script tag, you could addnscr.async = true;
. Anyway, this only works in cutting edge browsers.在这种情况下我会使用 JSONP。 Raymond Camden 提供了精彩介绍这个概念。
在这种情况下使用 JSONP 的快速示例位于 http://playground.itcouldbe9.com/syncjsonp/。
I would use JSONP in this case. Raymond Camden provides and excellent introduction to the concept.
A quick example of using JSONP in this situation is available at http://playground.itcouldbe9.com/syncjsonp/.
您可以将返回的代码封装在函数内,并在请求完成时执行该函数。例如,这是您的远程代码:
然后当您的请求完成时,您可以将该代码注入到 javascript 标记中,然后调用函数 hi()
You can have your code returned wrapped inside a function, and when the request completes, execute that function. For example, this is your remote code:
And then when your request is complete, you can inject that code into a javascript tag and then call the function hi()
为什么不使用回调?
编辑:
好的,然后尝试这个:
我认为剩下的唯一选择是轮询:
why not use a callback?
EDIT:
OK then try this:
I think the only option left would be polling: