This article will share with you a solution to problems that often need to be encountered. How can we make multiple jQuery exist on a page? This is the topic we need to discuss today. How can multiple jQuery coexist on one page? Like jquery-1.5 and jquery-1.11.
You may ask why multiple jQuery players need to coexist on one page? Can't I directly reference the latest version of jQuery?
The answer is, no. Because real life is cruel. Example:
The existing website has referenced jQuery 1.5 and related plug-ins. If you upgrade jQuery directly 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 jQuery version.
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 cannot be discarded. What should I do?
The method is to use jQuery's noConflict () to make multiple versions coexist.
When we import jQuery, jQuery only injects two variables into the global space of window:
The Code is as follows:
Window. $ = window. jQuery = {jQuery object };
Meanwhile, jQuery retains references to the old window. $ and window. jQuery objects. When we call:
The Code is as follows:
Var $ jq = $. noConflict ();
Window. $ is restored, but window. jQuery is still jQuery.
When we call:
The Code is as follows:
Var $ jq = $. noConflict (true );
Window. $ and window. jQuery are restored. Everything looks like jQuery has never been imported, but jQuery can be used through the variable $ jq.
Therefore, jQuery, which coexist with the old and new versions, can be implemented as follows:
The Code is as follows: