Beware the jQuery.noConflict() monster!
The intentions behind jQuery.noConflict() are good, but you will have problems if you are not careful.
Posted August 03th, 2012 in jquery
jQuery.noConflict() is the suggested way to use jQuery with other libraries.
Basically, it prevents jQuery to replace the $ variable with a reference to itself, so that you can still use some other $ based javascript library together with jQuery.
How does it work?
Try including Prototype and jQuery and print the $ variable.
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> console.log($); >>> function() <- this is jQuery, any code that expects Prototype to be on the $ variabile will fail </script>
But if you call the jQuery.noConflict() method, things will change.
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> jQuery.noConflict(); console.log($); >>> $(element) <- this is Prototype, not jQuery! console.log(jQuery); >>> function() <- this is jQuery, as expected </script>
So everything is cool and happy
Unlucky, it's not. If you rely on noConflict, you must be careful when including jQuery code from external sources - like your Wordpress plugins pool - because it is possible that the supercool plugin you wanna use uses the $ variable expecting jQuery, and not something else. Can you blame it?
Yes you can, because there is a super easy solution.
The solution
In the same page of the doc, they suggest to wrap your jQuery based code like this:
(function($) { /* some code that uses $ */ $(document).ready(function() { console.log("$", $); }); })(jQuery)
The above code declares a clousure (an anonymous function) which expects a $ parameter, and invokes it immediately passing the jQuery variable, which will be always available if you included jQuery no matter what.
Et voilat! You can now write jQuery code using the $ shortcut without worrying about the noConflict monster.
The only drawback of this tecnique is that you will not be able to refer to other $ based libraries inside the closure, but… is this a real issue? For me, it has never been :)
Have fun!