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

标签 javascript wordpress halt

我使用 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/

相关文章:

javascript - 为什么这种树形布局会给我带来无限循环?

javascript - Jquery 替换文本区域中的字符串

javascript - 如何将特定ID传递给嵌入式YouTube播放器?

php - 方法 POST 的 Wordpress REST API 自定义端点

delphi - 如何从包含 D2007 的异常 block 中使用 Halt(n) 返回错误代码?

java - 尽管在早期迭代中运行,但程序似乎卡住了

javascript - 仅在禁用 JavaScript 时显示 "Enable JavaScript"消息

javascript - Wordpress 子主题未通过 JQuery 应用样式

java - 使用标准端口在 Apache 和 Apache tomcat 之间共享 SSL