Jquery namespace collisions
Libraries other than jQuery may also use $ as an alias. This can cause interference between those libraries and jQuery.
To release $ for use with other libraries:
jQuery.noConflict();
After calling this function, $ is no longer an alias for jQuery. However, you can still use the variable jQuery itself to access jQuery functions:
jQuery('#hello').text('Hello, World!');
Optionally, you can assign a different variable as an alias for jQuery:
var jqy = jQuery.noConflict();
jqy('#hello').text('Hello, World!');
Conversely, to prevent other libraries from interfering with jQuery, you can wrap your jQuery code in an immediately invoked function expression (IIFE) and pass in jQuery as the argument:
(function($) {
$(document).ready(function() {
$('#hello').text('Hello, World!');
});
})(jQuery);
Inside this IIFE, $ is an alias for jQuery only.
Another simple way to secure jQuery's $ alias and make sure DOM is ready:
jQuery(function( $ ) { // DOM is ready
// You're now free to use $ alias
$('#hello').text('Hello, World!');
});
To summarize,
jQuery.noConflict() : $ no longer refers to jQuery, while the variable jQuery does.
var jQuery2 = jQuery.noConflict() - $ no longer refers to jQuery, while the variable jQuery does and so does the variable jQuery2.
Now, there exists a third scenario - What if we want jQuery to be available only in jQuery2? Use,
var jQuery2 = jQuery.noConflict(true)
This results in neither $ nor jQuery referring to jQuery.
This is useful when multiple versions of jQuery are to be loaded onto the same page.
<script src='https://code.jquery.com/jquery-1.12.4.min.js'></script>
<script>
var jQuery1 = jQuery.noConflict(true);
</script>
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script>
// Here, jQuery1 refers to jQuery 1.12.4 while, $ and jQuery refers to jQuery 3.1.0.
</script>