jQuery unveiled: the noConflict() method

The jQuery noConflict() method is used to avoid namespace collisions when using jQuery with other libraries. More specifically, this method avoid confusion when using JavaScript libraries which have a $() (dollar sign) syntax for retrieving elements or performing some private or public routines. Since $() is actually a synonym of jQuery(), a global namespace is created when the library is loaded (window.jQuery or window.$). Thus, this method performs the following operations:

noConflict: function( deep ) {
  window.$ = _$;

  if ( deep ) {
   window.jQuery = _jQuery;
  }

  return jQuery;
}

In simple terms, it replaces every instance of $ and jQuery with _$ and _jQuery, respectively. Anyway, if you know that other libraries will actually use the $ notation, you can change this:

$('#test')

to this:

jQuery('#test')

to avoid namespace collisions. For a better performance, you can store the jQuery object in a variable, like this:

var j = jQuery;
j('#test').html('Test');

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.