jquery Library Conflicts

Source: Internet
Author: User
Tags custom name jquery library

In an interview, the interviewer asked how the jquery and other library conflicts were resolved. Although I have seen it before, I can't remember it.

My idea is if let me design, then I will use a default value of $, do not pass parameters, then use $, and finally mounted on the window.$, the parameters are used to pass in the name, such as the incoming JQ, then I mounted on the WINDOW.JQ.

var mycontrol= "JQ";(function (name) {    var $=name | | " $"; The value of name exists $ is the value of name, does not exist or is a value of null,$ for the string "$"    console.log ($);    Window[$]=function () {        alert ("123");    }}) (mycontrol) Window[mycontrol] ();

In fact, this is certainly not a jquery solution to the conflict. Let's see how jquery solves the conflict.

Multiple Versions of jQuery or conflicts with other JS libraries are mostly common for $ symbols.

I. Resolution of the conflict 1, the same page jquery multiple version conflict resolution method
<body><!--introduced the 1.6.4 version of JQ--><script src= "Http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js "></script><script> var jq164 = Jquery.noconflict (true); </script><!--introduced the 1.4.2 version of JQ--><script src= "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/ Jquery.js "></script><script> var jq142 = Jquery.noconflict (true); </script><script> (function ($) {    //At this time the $ is jQuery-1.6.4    $ (' # ');}) (jq164);</script> <script>jq142 (function ($) {    //At this time the $ is jQuery-1.4.2    $ (' # ');}); </script>    </body>
2. The jquery library is imported after other libraries

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

1. jquery can be used instead of shorthand by full name of jquery

After the other libraries and the jquery library are loaded, you can call the Jquery.noconflict () function at any time to transfer control of the variable $ to another Javasript library. You can then use the jquery () function as a manufacturing facility for jquery objects in your program.

<script src= "Prototype.js" type= "Text/javascript" ></script><script src= "Jquery.js" type= "text/ JavaScript "></script><p id=" pp ">test---prototype</p><p>test---jquery</p>< Script type= "Text/javascript" >jquery.noconflict ();                The control of the variable $ is passed to Prototype.js, and the full name can not be called. jquery (function () {                    //uses jquery    jquery ("P"). Click (function () {        alert (jQuery (this). text ());    });}); /This can no longer be written as $, at which time the $ represents the $ symbol defined in Prototype.js. $ ("pp"). style.display = ' None ';        Using prototype</script>
2. Customize a shortcut

Noconflict () can return a reference to JQuery, which can be stored in a custom name, such as JQ, $J variable for later use.

This ensures that jquery does not conflict with other libraries and that you use a custom shortcut.

<script type= "Text/javascript" >var $j = Jquery.noconflict ();        Customize a short shortcut $j (function () {                        //Use jquery    $j ("P"). Click (function () {        alert ($j (this). text ());});})    ; $ ("pp"). style.display = ' None ';        Using prototype</script>
3, in the case of non-conflict still use $

If you want to use $ shorthand in a jquery block of code and do not want to change the shortcut, you can pass the $ symbol as a variable to the Ready method. This makes it possible to use the $ symbol within a function, while still having to use "jQuery" outside of the function.

<script type= "Text/javascript" >jquery.noconflict ();     Assign control of the variable $ to prototype.jsjquery (document). Ready (function ($) {    $ ("P"). Click (function () {        //Continue using the $ method        Alert (This). text ());});    /or the following jquery (function ($) {                    //using jquery    $ ("P"). Click (function () {        //Continue using the Method        alert ($ (this). Text ( ) );    });}); </script>

Or use the IEF statement block, which should be the best way to achieve full compatibility by changing the least amount of code.

We should use this notation when we write our own jquery plugins, because we don't know how to introduce the various JS libraries in the process of the work, and this block of statements can mask conflicts.

<script type= "Text/javascript" >jquery.noconflict ();                Assign control of variable $ to prototype.js (function ($) {                        ///define anonymous function and set formal parameter to $ $    (function () {                    ////anonymous function within $ all jquery        $ ("P") . Click (function () {    //Continue using the Method            alert ($ (this). text ());        })    ;}) (jQuery);                            Executes an anonymous function and passes the argument jquery$ ("pp"). style.display = ' None ';        Using prototype</script>
3. The jquery library is imported before other libraries

The jquery library is imported before other libraries, and the attribution default is owned by the following JavaScript libraries. Then you can use "jquery" directly to do some work on jquery.

At the same time, you can use the $ () method as a shortcut to other libraries. There is no need to call the Jquery.noconflict () function.

<!--introduced jQuery  --><script src= ". /.. /scripts/jquery.js "type=" Text/javascript "></script><!--introduced prototype  --><script src=" lib/ Prototype.js "type=" Text/javascript "></script><body><p id=" pp ">test-prototype (will be hidden) </p ><p >test-jquery (will be tied to order) </p><script type= "Text/javascript" >jquery (function () {   //Direct use JQuery, it is not necessary to call the "jquery.noconflict ()" function.    jquery ("P"). Click (function () {              alert (jQuery (this). text ());    });}); $ ("pp"). style.display = ' None '; Using prototype</script></body>
Second, principle 1, source code

Source: Look at the source of how to do

var//map over JQuery in case of overwrite_jquery = window.jquery,//map over the $ in case of overwrite_$ = Window.$,jque Ry.extend ({    noconflict:function (deep) {            if (window.$ = = = JQuery) {                window.$ = _$;            }            if (deep && window.jquery = = = JQuery) {                window.jquery = _jquery;            }            return jQuery;        }});

When JQuery is loaded, it gets to the current window.jquery through the pre-declared _jquery variable and gets to the current window.$ through _$.

Mount the noconflict under jquery by Jquery.extend (). So when we call, it's jquery.noconflict ().

2 judgments were made when calling Noconflict (),

The first if, turn over the control of the $.

The second if, at the time of the Noconflict () pass, the control of jquery is surrendered.

Finally Noconflict () returns the JQuery object, which parameter is received and which parameter will have control of jquery.

2. Verification
Conflict    var $ = 123;  Suppose other libraries are $123    $ (            function () {                console.log ($);//Error uncaught TypeError: $ is not a function            }    );

Resolve Conflicts

Resolve Conflict    var JQ = $.noconflict ();    var $ = 123;    JQ (function () {        alert ($);//123    });

Release $ Control Example

<script>    var $ = 123;//window.$ is 123, stored on a private _$. </script><script src= "Https://code.jquery.com/jquery-2.2.4.js" ></script><body><div >aaa</div><script>    var jq = $.noconflict ();//When window.$===jquery, assign _$ to window.$.    JQ (function () {        alert ($);//123    });</script>

Release jquery Control Example

Parameter deep function: Deep is used to abandon jquery external interface.

As below, noconflict () does not write parameters, and jquery is the constructor.

<script>    var $ = 123;    var jquery=456;</script><script src= "Https://code.jquery.com/jquery-2.0.3.js" ></script>< Body><div>aaa</div><script>    var jq = $.noconflict ();    JQ (function () {        alert (jQuery);//Constructor    });</script>

If you write a parameter true, it will pop up 456.

<script>    var $ = 123;    var jquery=456;</script><script src= "Https://code.jquery.com/jquery-2.0.3.js" ></script>< Body><div>aaa</div><script>    var jq = $.noconflict (TRUE);//When a true or a parameter is written, Deep is true window.jquery===jquery, so enter the IF condition. Assign a value of 456 to Window.jquery    JQ (function () {        alert (jQuery);//456    });</script>

The author starof, because the knowledge itself in the change, the author is also constantly learning and growth, the content of the article is not updated regularly, in order to avoid misleading readers, convenient tracing, please reprint annotated source: http://www.cnblogs.com/starof/p/6855186. HTML has a problem welcome to discuss with me, common progress.

jquery Library Conflicts

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.