Service

Using jQuery with Prototype

Many popular frameworks, CMS's and eCommerce platforms come preloaded with a JavaScript library like jQuery or Prototype. Most of the time, these systems heavily depend on those libraries for functionality on both the frontend and the backend; removing it or changing the variables it uses could severly break the site. This problem is particularly painful for developers who need to have Prototype and jQuery run side-by-side on the same site, as both try to overwrite the $, which is a critical variable that lots of code depends on.

Unfortunately, you can't just include both scripts onto the same page. Prototype essentially uses the $ variable as a shortcut to the document.getElementById() function. jQuery also likes to use $ as a shortcut/alias for the jQuery object. They both try to set the value of the $ variable, so whichever one library is included last will ultimately overwrite $.

Hello World!

Luckily the jQuery developers realized this type of scenario could occur, so they built in a safe-guard. If you call jQuery.noConflict() right after loading the jQuery library, it will immediately give the $ variable back to whoever had it first. The code example above would then look like this:

Hello World!

If you ever use these two libraries side-by-side, be sure to call jQuery.noConflict()!

But what if you already wrote code that assumes $ is assigned to jQuery? Do you need to replace every instance of $ with jQuery? Well you certainly could, but there's a much easier solution - use a closure!

var prototypeFunction = $;
var mainDiv = $('main');
(function($){
console.log($ === jQuery); // true
console.log($ === prototypeFunction); // false
console.log(mainDiv === $('main)); // false
})(jQuery);
console.log(mainDiv === $('main')); // true

Did you notice how the last two console.log() tests are identical but return different results? We're essentially saying "I want $ to refer to jQuery, but only within this chunk of code". JavaScript closures (aka self-executing functions) allow you to "rename"/reassign variables within that scope and not affect any outside code.