9

I am getting many errors in Sentry saying that "ReferenceError: jQuery is not defined", but still it occurs quite rarely in compare with total number of page loads.

<script src="/js/compiled/jquery.min-2fe08f7.js" defer></script>
<script src="/js/my-script-e6f35a4.js" defer></script>

Where my-script.js is something like:

(function($) {
    $('h1').text('Hello world');
})(jQuery);

but I have no clue from the Sentry report why the jQuery was not loaded.

The only clues given in Sentry breadcrumbs are pretty useless:

12:15:25 sentry ReferenceError: jQuery is not defined
12:15:25 sentry ReferenceError: jQuery is not defined
12:15:26 exception ReferenceError: jQuery is not defined

Deferred scripts should be loaded in the order they are present in the document, so I don't think that the problem is in asynchronous loading.

Maybe the jQuery file loading timeouts on some slow devices? or was the file unavailable on the server in some moment?

This happens to me in various JS files and also with various dependencies, not only jQuery. Can anyone advise me how to properly solve such problem, or at least get full console output to Sentry, including failed HTTP subrequests to resources like JS files, to find out what is the actual cause?

Thanks in advance.

amik
  • 5,613
  • 3
  • 37
  • 62
  • Get the URL from sentry and visit the page and (page source) check that have you included (jquery) file more than one time? or check ravan.js is must included after jquery file. – Firoz Tennali Feb 21 '19 at 09:19
  • According to another answer, _"you cannot trust defer"_ and _"In certain situations some browsers have a bug that causes `defer` scripts to run out of order."_ See: https://stackoverflow.com/a/10731231 – Dem Pilafian Mar 01 '19 at 21:18
  • Do you know which browsers it occurs on? https://stackoverflow.com/questions/32413279/defer-scripts-and-execution-order-on-browsers – andyhasit Jan 22 '21 at 19:34
  • Yes it might have been related to broken defer execution order. Thanks for posting probably a relevant reference for others, but now almost 4 years after I don't even remember on which project I was doing this :) – amik Jan 24 '21 at 09:40

1 Answers1

0

You want to wrap your code in an event handler that is fired only once the entire DOM is ready so it's guaranteed to run after all deferred scripts have been loaded.

Typically if jQuery were available this would be a $(document).ready() call, but since that's not guaranteed I would suggest doing something like this in your my-script.js file

document.addEventListener("DOMContentLoaded", function(event) {
   (function($) {
     $('h1').text('Hello world');
   })(jQuery);
});
Michael Angstadt
  • 880
  • 10
  • 18