How to continue javascript execution when an error occurs

I am using the native WP wp_enqueue_script () function for all my uploads script in both WP front and back-end so that it can handle duplicate calls with the same script, etc.

One problem is that other programmers don't use this feature and load their scripts directly from their code, which results in jQuery or jQuery-UI being loaded twice, leading to a lot of errors.

Another problem is that non-mine code triggers an error and stops JavaScript execution outside of this point.

In short:

The Javascript error occurs in code that does not belong to me.
Due to this error, my code is not executing.
I want my code to work around this error and still execute. Is there a way to deal with these problems?

+3


source to share


2 answers


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;
}

      



If you want to double-click the trigger of your pistol when needed;) check the flag to signal that the first shot was successful and avoid being fired from the backup. I think that under some circumstances your first shot can be taken even by a third party the code gets into the problem and fires the second shot.

+4


source


Not recommended at all, but you can use:

try {  
  //Some code likely to throw an error  
} catch (err) {}

      



This will allow something after you continue working, although you should catch the error too. The only time I haven't caught the error is when working with arrays and doing somearray[i-1]

where i-1

will be less than 0. This is just because it is cleaner than using conditionals to prevent it.

0


source







All Articles