How To Solve JQuery is undefined [Common Solutions 2018]

| 7 min. (1354 words)

When it comes to JavaScript and it’s libraries, one of the most annoying errors that pops up is jQuery is undefined.

The reason this can be such an annoying problem is there are a multitude of potential causes. I’ve seen more than my fair share of errors and exceptions, so I’d like to help you learn more about the jQuery is undefined error.

To get started I’ll go over some of the most common causes of the error and then dive into them individually to explain why it happens and how to fix the problem (or at least give you a few different options).

Common causes of ‘jQuery is undefined’

The most common causes of the jQuery is undefined error vary from being simple load ordering issues to the more vicious framework implementation ‘gotchas’ that can take a long time to track down, (unless you know about them ahead of time.)

Here are the top causes/situations where you’ll likely run into the jQuery is undefined problem:

  1. Incorrect load order of JavaScript assets.
  2. jQuery source can’t be loaded/found.
  3. Conflicting plugins/libraries/code.
  4. Framework implementation issues.

There are other potential causes for these errors but these four tend to be the most common. Knowing them can save you a tremendous amount of time (and a few headaches!) down the road.

#1 – Incorrect load order of JavaScript assets

This is often the most simple (yet overlooked) causes of jQuery being undefined. In this case, jQuery is being loaded but it’s coming after another library/script that attempts to use jQuery and expects it to be defined.

Below is an example of jQuery being loaded AFTER app.js which might contain references to jQuery which has not been loaded:

<html>
  <head>
    <script src="js/app.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  </head>
  <body>
    <p>Random filler text content.</p>
  </body>
</html>

Here you will see that we have moved jQuery to be loaded before the rest of our JavaScript, giving it access to jQuery after it has been loaded:

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="js/app.js"></script>
  </head>
  <body>
    <p>Random filler text content.</p>
  </body>
</html>

#2 – jQuery is not loaded/found

Another potential issue is if jQuery is not found and thus not loaded.  If you host your jQuery library on your own servers and something happens that prevents the local copy from being loaded,  jQuery will not be available.  

However, having to access a locally hosted copy of these files can lead to longer page load times for those not near the server location.

To speed up page load times we can use a CDN (content delivery network) like Google to host and provide JavaScript sources.  These services are great in providing improved page performance/load times and have a relatively high up time.

There are many arguments on whether you should or should not rely on local versus hosted/CDN options for your libraries but they are outside the scope of what we are covering here.  I personally prefer a blended approach that attempts to load the CDN version of the library but then checks afterward to see if jQuery was loaded.  If it hasn’t been loaded then a local copy is accessed.

Here’s an example of the CDN fallback code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="path/to/your/jquery_file.js"><\/script>')</script>

This will attempt to load the CDN version of jQuery and then check to see if jQuery is loaded.  If it is, nothing happens. But if window.jQuery does not return a value the code will attempt to load the locally hosted version.

#3 – Conflicting plugins/libraries/code

Sometimes third party code sources (plugins, libraries, and/or code snippets) can attempt to reassign variables or call them out of scope.

jQuery uses $ as a shortcut when referencing itself. This is normally fine but other developers sometimes assign $ in their own code. If this happens and your code (or another library) tries to reference jQuery via the $ shortcut, you will see the jQuery is undefined error pop up.

There are three ways to handle this with the third option being the more reliable and stable in most cases.

When jQuery is initialized it keeps track of the current value(s) of $. Calling jQuery.noConflict() restores those values, hopefully enabling other libraries/code to continue using $ as they see fit.

The issue with this method is that while it may free up $ for use, it might have unintended/unforeseen consequences with other libraries.

The [official jQuery API documentation][1] has a great example of this:

<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
  $.noConflict();
  jQuery( document ).ready(function( $ ) {
    // code that uses jQuery's $ goes here
  });
    // code that users another library's $ goes here
</script>

While .noConflict can just be used as is, you can also define a custom shortcut for jQuery as follows:

var j = jQuery.noConflict();

// Do something with jQuery
j( "div p" ).hide();

// Do something with another library's $()
$( "conent" ).style.display = "none";

*Courtesy of the [jQuery API documentation][1]

This will allow your code to reference jQuery without needing to worry about another application utilizing/reassigning $.  The rough part is making sure that the variable you use is not currently in use elsewhere. This is worth the effort, as it will cause less issues down the road.

This option is to scope $ for jQuery to use in your own code. To do this, you need to declare an anonymous function that takes jQuery as an argument. Next, reference the function via $ in the scope/context of your anonymous function.

(function($) {
  'use strict';

  $(function() {
    // your code here
  });
})(jQuery);

This will allow you to use $ as you need to without causing issues with other code’s usage of the function. To some developers this will be considered a common sense best practice, but not everyone knows about it so we wanted to make sure it was covered.

#4 – Framework implementation issues

This issue can be related to both load order and conflicts with other code sources. Many consider placing all necessary JavaScript references right before the closing body tag. This prevents slow JavaScript files increasing page load time. The jQuery is undefined issue can creep up if a framework (like [Joomla][2] or [Zend][3]) loads external scripts in the head of your pages while your jQuery is still at the bottom of the body tag. This potentially leads to jQuery being referenced before it has loaded.

Most frameworks try to handle this for you by loading jQuery in the head as well, despite it potentially leading to some slowdown. But in the off chance you’re still seeing the jQuery is undefined error and you’ve tried our previous suggestions, take a few minutes to do some research into your frameworks to see how they load JavaScript into your pages.

Summary and further tips

As you can see there are a variety of different things that can cause the jQuery is undefined error. A few of them are easy fixes but when you start dealing with external libraries, third party code sources, and frameworks it quickly becomes a maze of tracking down load orders and dependencies.

The best strategy to diagnose these issues is to start with the simple load order checks and then progress to the more in-depth causes. Never assume that something is being loaded where it should be unless you wrote the code yourself and tested it. The ‘magic’ that frameworks and external libraries provide is amazing to speed up productivity but can also be sources of unknown conflicts/issues.

Do you have any other tips or common causes that you think we should add here or address separately? Let us know in the comments!

-Solve jquery no conflict -jquery tutorial