Search code examples
javascriptwordpresshalt

How to continue javascript execution when an error occurs


I use the WP native function wp_enqueue_script() for all my script loading in both WP front and back-end so it can handle duplicated calls to the same script and so on.

One of the issues is that other programmers don't use this function and load their scripts directly from their code, which causes jQuery or jQuery-UI to be loaded twice, leading to a bunch of errors.

The other issue is that code not owned by me triggers an error and stops the execution of JavaScript beyond this point.

In short:

A Javascript error occurs in code not owned by me.
My code doesn't execute due to that error.
I want my code to bypass that error and still execute.
Is there a way to handle these issues?


Solution

  • 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 pull the trigger of your gun twice just when necessary ;) set a flag to signal that the first shot was successful and avoid the backup shot, I think that under some circumstances your first shot could be executed even third party code get in trouble and trigger the second shot.