Uncaught ReferenceError: jQuery is not defined

When you write custom Javascript for Joomla! it can occur that jQuery is loaded after your script is loaded. This makes your script worthless as it throws the error "Uncaught ReferenceError: jQuery is not defined" and your code won't execute anymore. There are simple solutions for this problem!

Waiting Function

You can use a function to wait until the global jQuery object is found on the window object. This means that jQuery is loaded and can be used. If you use a function that waits for it to be loaded and then execute your code, you can never get exceptions about jQuery not being loaded. The function is simple and looks like this:

This code will be executed immediately if jQuery is already loaded. If not, it will wait 25 milliseconds and check again. If jQuery is found after the waiting period, it'll execute your function meaning your script can always use jQuery without problems. The only downside to this is when jQuery is never loaded; the script will just wait forever.

Fallback

You can provide a callback if the jQuery library did not load at all. All the scripts, if async is not specified, are blocking your website because it waits for the scripts to load. This means that if jQuery is still not loaded even after parsing the page something bad happened. The CDN could've been down, lagging or simply blocked due to country-specific laws. Your own jQuery script could've been accidentally removed by someone else or your webserver did not respond the way you've wanted it to. Luckily, there is a simple solution. You just place the following code at the bottom of your website before the closing body tag:

This means that whenever jQuery is not loaded, thus not found in the window object, a script will be placed at the bottom of your page loading jQuery in from another location. If you combine this with the waiting function, it can only go wrong whenever both locations fail to serve jQuery. Even then, the console won't show an exception; your code just won't run at all.

Combining the two

If you combine the code and alter the first function, you can check if jQuery has been loaded after 3 seconds (which should be the maximum loading time for any page these days). If it didn't, you can load jQuery from a different location. This is in fact the same solution as the fallback, but in a simple function. Downside to this is that your script must be loaded for jQuery to be included when it didn't. The new updated code will be;

Overview

Company

Connect

Facebook

SnoerenDevelopment.nl is not affiliated with or endorsed by the Joomla Project or Open Source Matters. The Joomla name and logo are used under a limited license granted by Open Source Matters the trademark holder in the United States and other countries.