As you know, jQuery uses the $ sign as a quick shortcut or alias for the word jQuery.
However, there are many other popular JavaScript frameworks out there.
Frameworks like Angular, Backbone, and Knockout also use the $ sign as a shortcut!
If two different libraries are included on the same webpage, and both use the $ sign, things will break.
The browser won't know which library the $ belongs to, resulting in massive script errors.
Fortunately, the jQuery team anticipated this issue and created a built-in solution.
The $.noConflict() method releases the hold on the $ shortcut identifier.
This allows other JavaScript scripts and libraries to safely use the $ sign.
After calling noConflict(), you can still use jQuery, but you must type out the full word jQuery.
$.noConflict();
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery("p").text("jQuery is still working!");
});
});
Typing out the full word jQuery every time can be tedious.
You can easily create your own custom shortcut by assigning $.noConflict() to a variable.
var jq = $.noConflict();
jq(document).ready(function(){
jq("button").click(function(){
jq("p").text("Using the custom 'jq' shortcut!");
});
});
There is a smart trick to continue using the $ sign, even after calling noConflict().
You can pass the $ sign as a parameter directly into the ready function.
This allows you to use $ locally inside the function block, while external scripts use $ elsewhere.
$.noConflict();
jQuery(document).ready(function($){
// You can safely use $ here
$("button").click(function(){
$("p").text("Using $ safely inside the block!");
});
});
What is the primary purpose of the $.noConflict() method?
Can you assign the noConflict() method to a custom variable name like 'myJq' to use instead of '$'?