Errors in scripts loaded with jQuery $.getScript

Spent some time the other day trying to figure out why I wasn’t seeing JavaScript errors in certain files where I expected to, which was problematic both for development and also for the monitoring of client-side errors we’re doing in the application (assigning a handler to window.onerror that makes an ajax call with error information to an endpoint for this purpose).

Basically, if there are errors in any of the scripts you are loading with $.getScript, or the full $.ajax call for which $.getScript is shorthand, these will be caught by jQuery and will fail to show up in the console or be passed to any window.onerror handler you’ve defined. jQuery provides a global ajaxHandler you can attach to, for example, document, which you can then use to do whatever client-side error handling/logging you want to do.

The downside of this approach is (as far as I can tell) that you don’t get quite as much error information (specifically, the line number of the error) from jQuery as you do from other ways of loading scripts with js, because the error gets caught during a call to eval (or more specifically, jQuery’s globalEval method).

2 thoughts on “Errors in scripts loaded with jQuery $.getScript”

  1. Hell yeah, this my problem. But even if I’m using .ajaxError handler, I’m not able to get error line of code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.