发生错误时如何继续执行javascript

dio*_*ney 2 javascript wordpress halt

我使用 WP 本地函数 wp_enqueue_script() 在 WP 前端和后端加载我的所有脚本,因此它可以处理对同一脚本的重复调用等等。

问题之一是其他程序员不使用此功能并直接从他们的代码加载他们的脚本,这会导致 jQuery 或 jQuery-UI 加载两次,从而导致一堆错误。

另一个问题是不属于我的代码会触发错误并在此之后停止 JavaScript 的执行。

简而言之:

不属于我的代码中出现 Javascript 错误。
由于该错误,我的代码没有执行。
我希望我的代码绕过该错误并仍然执行。
有没有办法处理这些问题?

小智 5

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;
}
Run Code Online (Sandbox Code Playgroud)

如果您想在必要时扣动扳机两次;) 设置一个标志以表示第一次射击成功并避免备用射击,我认为在某些情况下,即使第三方代码进入,您的第一次射击也可以执行麻烦并触发第二枪。