是否有任何替代方法可以使用 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 之前执行。它也是从同一域上的服务器加载的,因此它是可信的。

最佳答案

动态脚本文本插入是 eval 的唯一替代方法。

var head    = document.getElementsByTagName('head')[0] || document.documentElement,
    nscr    = document.createElement('script');

    nscr.type           = 'text/javascript';
    nscr.textContent    = o.responseText;
    nscr.setAttribute('name', 'dynamically inserted');
    nscr.onload         = nscr.onreadystatechange = function() {
              if( nscr.readyState ) {
                   if( nscr.readyState === 'complete' || scr.readyState === 'loaded' ) {
                      nscr.onreadystatechange = null;
                       doSomethingWithCode();
              }
              else {
                  doSomethingWithCode();
              }
    };

    head.insertBefore(nscr, head.firstChild);

唯一要提的是:textContent 在 InternetExplorers 中不可用。您需要在那里使用 .text ,因此对其进行一些检测使其跨浏览器兼容。

编辑

要让 syncronous 加载动态脚本标签,您可以添加 nscr.async = true; 。无论如何,这仅适用于尖端浏览器。

关于javascript - 用于运行远程代码的 eval 的替代方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4605073/

10-11 11:19