Introduction to how to quickly resolve conflicts between jQuery and other libraries

  • 2020-03-30 01:10:54
  • OfStack

In general, the definition of the global name $is the biggest bone of contention and conflict when using jQuery and other libraries on the same page. JQuery is known to use $as an alias for the jQuery name and for every function jQuery exposes, but other libraries, most notably Prototype, also use the $name.

1. JQuery provides the $.noconflict () utility function to waive the use of the $identifier so that other libraries can use it.

The syntax of this function is as follows:
$. Of noConflict (jqueryToo)

Returns control of the identifier $to other libraries, allowing you to mix jQuery with other libraries on the page. Once the function is executed, the function must be called using the jQuery identifier instead of the $identifier,

You can also drop jQuery identifiers (optional)

This method should be called after jQuery is included, but before the collision library is included.


Although the jQuery identifier is used, because $is an alias for jQuery, all jQuery functionality is still available after $.noconflict () is applied. We can define shorter, conflict-free jQuery aliases, for example

Var  $j = jQuery;

2. Another common usage is to create a scope environment, $identifier in the environment to the jQuery object, it is a commonly used technique in extend jQuery, especially for plugin authors, if they can't be for page developers have called $. Of noConflict () to make any assumption, of course, also can't call this function to avoid damage by page developers will,

This idiom is used as follows:
(function ($) {}) (jQuery);
(function ($) {})

This section declares a function enclosed in parentheses to generate an expression whose result is a reference to an anonymous function that expects to pass in a single argument and name it $. In the body of the function, you can use the $identifier to refer to anything passed to the function. Because the argument declaration takes precedence over any similar named identifier in the global scope, any $value defined outside the function is replaced by the passed argument inside the function.

(jQuery)

Function calls are made on anonymous functions, passing jQuery objects as arguments


On the outside of the function, whether or not the $identifier is already defined in Prototype or some other library, in the body of the function it always points to the jQuery object.

When using this technique, externally declared $is not available in the body of the function.

3. A variation of the second usage is also often used to declare ready handlers, resulting in a third syntax,
JQuery (function ($) {
})

It is best to take this precaution with the definition of $when writing reusable components that might be used on pages that already use $.noconflict ().


Related articles: