Home > Article > Web Front-end > Solutions for coexistence of multiple jQuery versions_jquery
How to let multiple jQuery coexist on one page? Such as jquery-1.5 and jquery-1.11.
You may ask, why do you need multiple jQuery to coexist on one page? Isn’t it possible to directly quote the latest version of jQuery?
The answer is, no. Because real life is very cruel. Give me an example:
Existing websites have already referenced jQuery 1.5 and related plug-ins. If you directly upgrade jQuery to the latest version, these plug-ins will not work unless you can upgrade all these plug-ins, or wait for the author of each plug-in to release a version that supports the latest version of jQuery.
Now, if we want to develop new plug-ins or write JavaScript code based on jQuery, using the new version will save time and effort.
But the old version must not be thrown away, what should I do?
The method is to use jQuery’s noConflict() to allow multiple versions to coexist.
When we import jQuery, jQuery only injects two variables into the global space of window:
At the same time, jQuery internally retains references to the old window.$ and window.jQuery objects. When we call:
window.$ is restored, but window.jQuery is still jQuery.
When we call:
Both window.$ and window.jQuery are restored, and everything looks like jQuery has never been imported, except that jQuery can be used through the variable $jq.
So, allowing new and old versions of jQuery to coexist can be implemented like this:
In myscript.js, use $jq to access the 1.11 version of jQuery.
At this point, the problem is solved.
However, after introducing two versions of jQuery, the page was messed up. What if someone doesn’t understand the code and deletes var $jq = jQuery.noConflict(true);? Or, if you swap the two lines that import jQuery, you won't get the correct jQuery version in the end.
The best way is to directly quote the new js file we wrote without changing the page:
In this way, we will reference the latest version of jQuery inside myscript.js, and we don’t care whether the page has jQuery or not, and which version of jQuery there is.
Start writing new and better solutions. First, determine the main body of myscript.js:
It is a good habit to use anonymous functions to avoid polluting global variables and prevent external code access.
The next step is to embed the jQuery 1.11 code directly:
The embedded code is of course the compressed code, 3 lines in total, and then add:
Note that $ is a local variable. You can reference this $ at any time in the following code. It is not the same object as the global variable $ of jQuery in other versions of the page.
The last step is to check whether the jQuery protocol allows us to embed the jQuery source code directly into our own JavaScript code.
The above is the entire content of this article, I hope you all like it.