Web App Development

How does jQuery.noConflict work?

The noConflict function in jQuery lets you use multiple versions of jQuery on the same page or load other libraries that also have a $ function.

The code in jQuery 1.7.2

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

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

return jQuery;
}
The code is quite easy to understand, once you know that when jQuery is loaded it puts backups of window.$ and window.jQuery into _$ and _jQuery.
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,

// Map over the $ in case of overwrite
_$ = window.$,

Return jQuery

This returns the jQuery function that jQuery uses internally. This way, when you use $.noConflict(true), you can use the return value as your $ function - because window.jQuery will be overwritten.

Why the if's?

If noConflict wouldn't check that the global object actually stores a reference to jQuery it could overwrite another library. Imagine you
  1. Load jQuery
  2. Call noConflict
  3. Load another $ function library
  4. Accidentally call noConflict again
This would set the $ function of the other library to undefined. (You're right if you think that this is not a very likely scenario. Some earlier version of jQuery didn't even do this check.)
window.$ is compared with jQuery rather than $ because internally jQuery only uses the local jQuery variable. $ is only used when exposing the jQuery object to window.

Comments


Follow me on Twitter