jQuery.noConflict() - Multiple Javascript Libraries

When working on a project we normally decide on a Javascript library and stick to it. Sometimes for one reason or another there just isn’t anything we can do and a second library needs to be introduced. If you’ve ever tried this, you know that if you’re not careful you will have a hot mess on your hands.

Recently I was working on a project where all the Javascript worked fine in the static templates, but had issues when integrated with the CMS. The templates were using jQuery and the CMS was automatically adding Prototype to the page output. First thing I say is, “No problem, I’ll just use jQuery’s noConflict mode.” After making the change I was still seeing errors. After digging around I saw that our site’s main Javascript file was using the $ variable… hmmm…

To make your life easier wrap your code in an anonymous function and pass the jQuery variable in. This is probably more obvious if you’re writing some code others will use like a jQuery plugin, but could help save your ass down the line.

This is what your site’s main.js probably looks like

$(document).ready(function() {
    // Do awesome stuff...
});

Adding the anonymous function and passing the jQuery variable in will prevent problems later with the $ variable.

(function($){
    $(document).ready(function() {
        // Do awesome stuff...
    });
})(jQuery);