JQuery is a way to avoid collisions between $and other JS libraries

  • 2020-03-30 02:05:40
  • OfStack

JQuery requires the use of the $sign, and if other js libraries (such as the well-known prototype) also define the $sign, it will cause a conflict, which will affect the normal execution of js code. Jqeury offers some ways to avoid this problem. Let's see what the differences are

Plan 1:
Introduce noConflict(), replacing $with another symbol
var $j = jQuery.noConflict(); 
alert("Text: " + $j("#test").text()); 

Disadvantage: after introducing this code, not only the current js file, but all the js referenced by this HTML, if it is useful to the $in jquery, will have to replace the previous $with $j

Scheme 2:
The ready function is jquery's entry function, and it can
The $(document). Ready (function () {
JQuery (document). Ready (function ($) {}
Disadvantages: only valid for code that is nested in ready, not for code that is nested outside. If all your logic is in the ready function, that's fine. But we usually write some subfunctions outside of the ready function, and then the ready function calls those functions. This scheme is not valid for these functions, so it has limitations.

Solution 3 (recommended, especially when developing js plug-in) :

Give the js content package a function
//Your js code is placed here (such as the ready function and subfunctions mentioned in the second scenario)
//If it's a js file, you're just adding a line of code to the header and the tail of the file

(function($) { 
//Your js code

This method, without the drawbacks of the above two schemes, only affects the code wrapped in jQuery(function($){}.
It's important that it doesn't affect other js code. Imagine that if you write a js public component that USES jquery, you need to consider $sign collisions in order to improve robustness. If you use scenario 1, others will have to comply with your agreement to change the $in your js code to $. If you use scenario 3, you can avoid the impact of $conflict on the component without requiring people who use public components to modify their code.

Related articles: