JQuery. noConflict () and jquery. noconflict

Source: Internet
Author: User

JQuery. noConflict () and jquery. noconflict

JQuery is currently 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 pollution, jQuery provides the jQuery. noConflict () method to resolve variable conflicts. This method is undoubtedly very effective. Unfortunately, jQuery's official documentation does not clearly describe this method, and many developers do not know when they call jQuery. what happened when noConflict () occurs, resulting in many problems during use. Despite this, the implementation principle behind jQuery. noConflict () is still worth learning by Web developers and becomes a powerful tool to solve problems similar to global namespace pollution.

What is the role of jQuery. noConflict?

JQuery. noConflict () has only one purpose: it allows you to load multiple jQuery instances on the same page, especially different versions of jQuery. You may wonder why you need to load/use multiple jQuery objects of different versions on a page? Generally, there are two cases. First, your business code uses the latest jQuery library, and the third-party plug-ins you choose depend on earlier jQuery libraries. Second, you are maintaining a system, its Existing Business Code references older jQuery libraries for various reasons. Your newly developed modules use jQuery libraries of other versions. In either case, you have to deal with jQuery object/method conflicts. Fortunately, jQuery. noConflict () helps you solve this problem.

What happens when jQuery is loaded?

When jQuery is referenced/loaded by pages, it is encapsulated in an self-executed function (anonymous function, all the variables, functions, and objects it provides are in the executable environment of anonymous functions, and the external environment cannot be called to prevent global namespace pollution.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 

JQuery defines two global objects in the anonymous function: jQuery and $, and exposes itself to the external environment. The various public libraries used by the developer are implemented 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, and use it to access private variables and functions inside the anonymous function. This makes the private variables and functions of anonymous functions remain in the memory after self-execution, and will not be cleared by the garbage collection mechanism of javascript.

window.jQuery = window.$ = jQuery; 

After jQuery is loaded by the page, the current page may already have the jQuery and $ global variables (for example, when other third-party libraries are loaded, they are also defined internally ), this will cause existing objects to be overwritten (global namespace pollution ). To solve this problem, jQuery caches existing global variables internally and stores them in private variables _ jQuery and _ $ for future calls. Therefore, if the jQuery and $ objects do not exist when the page loads the jQuery library, _ jQuery and _ $ are both undefined; otherwise, they both save references to existing jQuery and $ (maybe from a third-party library referenced earlier or a different version of jQuery library ). Then, jQuery overwrites the two global variables and exposes itself to the external environment as described above. Now, the global variables jQuery and $ on the page point to the newly introduced jQuery library.

// Map over jQuery in case of overwrite_jQuery = window.jQuery,// Map over the $ in case of overwrite_$ = window.$,// Otherwise expose jQuery to the global object as usualwindow.jQuery = window.$ = jQuery; 

What is the magical effect of jQuery. noConflict?

Assume that the system you maintain has referenced the jQuery library of version 1.7.0, And you have referenced the jQuery library of version 1.10.2 in the newly added function. So, is there a way to re-use jQuery 1.7.0 or two versions of jQuery Library at the same time? The answer is yes, that is jQuery. noConflict (). Actually, with jQuery. noConflict (), you can immediately point the global variables jQuery and $ to the referenced objects. Amazing, right? This is why jQuery caches the referenced objects before exposing itself.

Optional values jQuery. noConflict () accepts an optional Boolean parameter. The default value is false. What is the impact of this parameter? In fact, it is very simple. If you call jQuery. noConflict () or jQuery. noConflict (false), only the global variable $ will be reset to the previous reference value; If jQuery is called. noConflict () or jQuery. noConflict (true), then the global variables jQuery and $ are reset to the previous reference value. This is very important and we recommend that you keep it in mind. When you call jQuery. noConflict (false/true), it returns the current jQuery instance. With this feature, we can rename jQuery.

// "Renaming" jQueryvar jayquery = jQuery.noConflict( true );// Now we can call things like jayquery.ajax(), jayquery.css(), and so on

Let's take a look at the code snippet to see if we really understand the magic 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 jQuery 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><!-- jQuery now points to jQuery 1.7.0; $ now points to jQuery 1.10.2; jquery164 points to jQuery 1.6.4 --> 

Avoid conflicts with third-party Libraries

The code snippet above demonstrates how to solve the conflict between multiple versions of jQuery. Next, we try to solve the conflict between the jQuery Library and the third-party library. The following code snippets are available in jQuery's official documentation, if you are interested, you can read the official documents carefully to find out the differences.

Use the No-Conflict mode directly

Using the No-Conflict mode is actually renaming jQuery and then calling it.

<! -- No-conflict mode, jquery. js in prototype. js is introduced later. --> <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 () ;}); // $ is redirected to prototype again. object defined in js // document. getElementById (). mainDiv below is a DOM element, not a jQuery object. window. onload = function () {var mainDiv =$ ("main") ;}</script>

Use self-executed function Encapsulation

In this way, you can continue to use the standard $ object within the anonymous function, which is also used by many jQuery plug-ins. Note that with this method, the function cannot use the $ object defined by prototype. js.

<! -- Jquery. js in prototype. js is introduced later. --> <script src = "prototype. js "> </script> <script src =" jquery. js "> </script> <script> jQuery. noConflict (); (function ($) {// Your jQuery code here, using the $}) (jQuery); </script>

Use the standard jQuery (document). ready () function

If the jQuery library is introduced before other libraries, the jQuery and $ internally defined by jQuery will be overwritten by third-party libraries. At this time, it makes no sense to use noConflict. The solution is simple, and jQuery's standard call method is used directly.

<! -- Jquery. js in prototype. js was introduced before. --> <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. jswindow. onload = function () {var mainDiv =$ ("main") ;}; </script>

The following describes the jQuery noConflict () method.

The noConflict () method releases the control of $ identifier, so that other scripts can use it.

Instance

Of course, you can still use jQuery by replacing the abbreviation with the full name:

$. 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 () returns a reference to jQuery. You can save it to a variable for later use. See 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 the $ Abbreviation and you do not want to change this shortcut, you can pass the $ symbol as a variable to the ready method. In this way, you can use the $ symbol in the function. In addition to the function, you still have to use "jQuery ":

$. NoConflict (); jQuery (document ). ready (function ($) {$ ("button "). click (function () {$ ("p "). text ("jQuery is still running! ");});});
Articles you may be interested in:
  • "JQuery" Name Conflict is solved using noConflict
  • NoConflict () method in jQuery
  • Jquery plug-in conflict (jquery. noconflict) Solution
  • Implementation principle decomposition of noconflict functions in jQuery
  • Examples of noConflict () usage in jQuery
  • JQuery. noConflict ()

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.