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