我使用WP native函数WP_enqueue_script()在WP前端和后端加载我的所有脚本,以便它可以处理对同一脚本的重复调用等。
其中一个问题是,其他程序员不使用这个函数,直接从代码中加载脚本,这会导致jQuery或jQuery UI被加载两次,从而导致一堆错误。
另一个问题是,不属于我的代码会触发一个错误,并在此之后停止JavaScript的执行。
简而言之:
在不属于我的代码中发生Javascript错误。
由于那个错误,我的代码没有执行。
我希望我的代码绕过那个错误,仍然执行。
有办法解决这些问题吗?

最佳答案

function ShieldAgainThirdPartyErrors($) {
    // Code you want protect here...
}

// First shot.
// If no error happened, when DOMContentLoaded is triggered, this code is executed.
jQuery(ShieldAgainThirdPartyErrors);

// Backup shot.
// If third party script throw or provoke an unhandled exception, the above function
// call could never be executed, so, lets catch the exception and execute the code.
window.onerror = function () {

    ShieldAgainThirdPartyErrors(jQuery);

    return true;
}

如果你想在必要的时候扣两次枪的扳机;)设置一个标志,表明第一枪成功,并避免第二枪,我认为在某些情况下,你的第一枪可以执行,甚至第三方代码陷入麻烦并触发第二枪。

关于javascript - 发生错误时如何继续执行JavaScript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14676989/

10-09 17:57
查看更多