Three minutes to show you around. Jquery.noconflict () _jquery

Source: Internet
Author: User
Tags anonymous garbage collection jquery library

jquery is one of the most widely used front-end frameworks, with a large number of third-party libraries and Plug-ins developed based on it. To avoid global namespace contamination, jquery provides a jquery.noconflict () method to resolve variable conflicts. This method, no doubt, is very effective. Unfortunately, the official jquery document does not have a clear description of the method, and many developers do not know exactly what happened when they called jquery.noconflict (), causing many problems when they were used. Still, the principle behind jquery.noconflict () is still worth the learning of Web developers as a tool for solving problems like global namespace pollution.

The role of Jquery.noconflict ()?

Jquery.noconflict () exists for one purpose only: it allows you to load multiple jquery instances on the same page, especially in different versions of jquery. You may find it strange why you should load/use multiple different versions of JQuery objects on a page. Generally speaking, there are two kinds of situations. In the first case, your business code uses the latest version of the jquery library, and your Third-party plug-in relies on an earlier version of the jquery Library; in the second case, you are maintaining a system in which the existing business code references an older version of the jquery library for a variety of reasons, Your newly developed module uses a different version of the jquery library. In either case, you have to face the problem of jquery object/method conflict. Luckily, Jquery.noconflict () helped you solve the problem.

What happens when jquery is loaded?

When jquery is referenced/loaded by the page, it is encapsulated in a self executing function (anonymous function) that provides all of the variables, functions, objects within the executable environment inside the anonymous function, and the external environment cannot be invoked to prevent global namespace contamination.

 
 

jquery defines two global objects within the anonymous function: jquery and $, exposing itself to the external environment. Various common methods used by developers are accessed through these two objects, such as Jquery.ajax (), Jquery.css (), and so on. Initially, they point to the same object jquery (private variable) inside the anonymous function, which accesses the private variables and functions inside the anonymous function. This allows the anonymous function to remain in memory with its internal private variables and functions since it was executed, and will not be purged by JavaScript's garbage collection mechanism.

 
 

When jquery is loaded by the page, the current page may already have jquery and $ two global variables (for example, loading other third-party libraries and defining them internally), which can cause existing objects to be overwritten (global namespace pollution). To solve this problem, jquery caches the existing global variables internally and saves them in the private variables _jquery and _$ for subsequent calls. So, if the page does not have jquery and $ objects when it loads the jquery library, then _jquery and _$ are undefined, otherwise they will save references to existing jquery and $ (perhaps from a third-party library or a different version of the jquery library). After that, jquery overwrites the two global variables as described above and exposes itself to the external environment. At this point, the global variables jquery and $ on the page are already pointing to the jquery library just introduced.

Map over JQuery into case of overwrite
_jquery = window.jquery,
//Map over the $ in case of overwrite
_$ = w indow.$,
//Otherwise expose jQuery to the global object as usual

The magical Effect of jquery.noconflict ()?

Suppose you maintain a system that already references the 1.7.0 version of the jquery library, and you are referencing the 1.10.2 version of the jquery library in the newly added functionality. So is there a way to reuse jquery 1.7.0 or to use two versions of the jquery library at the same time? The answer is yes, that is jquery.noconflict (). In fact, using jquery.noconflict (), you can immediately reset the global variable jquery and $ to the previously referenced object. Isn't it amazing? This is why jquery caches previously referenced objects before exposing itself to outsiders.

Jquery.noconflict () accepts an optional Boolean parameter, usually the default value is False. What effect does this parameter have? Actually, it's very simple. If you call Jquery.noconflict () or jquery.noconflict (false), only the global variable $ is reset to the previous reference value if you call Jquery.noconflict () or Jquery.noconflict (TRUE), the global variable jquery and $ are reset back to the previous reference value. This is very important, and the recommendations are kept in mind. When you call Jquery.noconflict (false/true), it returns an instance of the current jquery, which enables us to rename jquery.

"Renaming" JQuery
var jayquery = Jquery.noconflict (true);
Now we can call things like Jayquery.ajax (), Jayquery.css (),

Let's take a look at a snippet of code and test to see if we really understand the magical noconflict ()

<!--JQuery and $ are undefined-->
<script src= "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/ Jquery.min.js "></script>
<!--jquery and $ now point to jquery 1.10.2-->
<script src="/ Ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js ">
<!--jquery and $ now point to jquery 1.7.0-->
<script>jquery.noconflict ();</script>
<!--jquery still points to jquery 1.7.0; $ now points to J Query 1.10.2-->
<script src= "//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" >
<! --jquery and $ now point to JQuery 1.6.4-->
<script>var jquery164 = Jquery.noconflict (true); </SCRIPT&G T

Avoid conflicts with third party libraries

The code snippet above shows how to resolve multiple versions of jquery's conflict. Next, we try to resolve the conflict between the jquery library and the third party library, where the code snippet appears in the official jquery document, and interested programs apes can read the official document to see the difference.

Direct use of No-conflict mode

Using the no-conflict mode, you're actually renaming jquery, and then calling.

The <!--adopted no-conflict mode, Jquery.js was introduced after Prototype.js. -->
<script src= "prototype.js" ></script>
<script src= "Jquery.js" ></script>
<script>
var $j = jquery.noconflict ();
$j references the jquery object itself.
$j (document). Ready (function () {
$j ("div"). Hide ();
});
The $ is again pointed to the object defined in Prototype.js
//document.getElementById (). Maindiv below is a DOM element, not a JQuery object.
Window.onload = function () {
var maindiv = $ ("main");
}

Encapsulating using a self-executing function

In this way, you can continue to use the standard $ object within the anonymous function, which is also the method used by many jquery plug-ins. It should be noted that, using this method, the $ object defined by Prototype.js can no longer be used inside the function.

<!--Jquery.js was introduced after Prototype.js. -->
<script src= "prototype.js" ></script>
<script src= "Jquery.js" ></script>
<script>
jquery.noconflict ();
(function ($) {
//Your jquery code here, using the $
}) (jquery);

Use standard jquery (document). Ready () function

If the jquery library was introduced before other libraries, jquery and $ defined within jquery would be overwritten by Third-party libraries, and it would be meaningless to use noconflict (). The solution is simple, using the standard invocation method of jquery directly.

<!--Jquery.js was introduced before Prototype.js. -->
<script src= "jquery.js" ></script>
<script src= "Prototype.js" ></script>
<script>
//Use full jquery function name to reference jquery.
jquery (document). Ready (function () {
jQuery ("div"). Hide ();
});
or
jquery (function ($) {
//Your jquery code here, using the $
});
Use the $ variable as defined in prototype.js
window.onload = function () {
var maindiv = $ ("main");
} ;
</script>

Let me introduce the jquery noconflict () method

The Noconflict () method frees up the control of the $ identifier so that other scripts can use it.

Instance

Of course, you can still use JQuery with your full name instead of shorthand:

$.noconflict ();
jquery (document). Ready (function () {
jquery ("button"). Click (function () {
jquery ("P"). Text ("jquery is still running!"). ");
});
});

Instance

You can also create your own shorthand. Noconflict () can return a reference to JQuery, which you can deposit into a variable for later use. Take a look at this example:

var JQ = $.noconflict ();
JQ (document). Ready (function () {
JQ ("button"). Click (function () {
jq ("P"). Text ("JQuery is still running!"). ");
});
});

Instance

If your JQuery code block uses $ shorthand, and you don't want to change the shortcut, you can pass the $ symbol as a variable to the Ready method. This allows you to use the $ symbol within the function-and, beyond the function, you still have to use JQuery:

$.noconflict ();
jquery (document). Ready (function ($) {
$ ("button"). Click (function () {
$ ("P"). Text ("JQuery is still running!") ");
});
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.