简体   繁体   中英

In a userscript/greasemonkey, how do you use a newer version of jQuery when the website already uses an older version?

I'm trying to write a userscript for a website that is already using an ancient version of jQuery. If I @require a modern version in the userscript, I get a console error about how a field named exists doesn't exist. Since these two versions of jQuery are incompatible, is there any way to use them both without them conflicting?

Maybe there's an even better solution than this, but here's what I've come up with: @require jQuery the way you'd normally want, then at the end of your script, put a $.noConflict(); . As some of your userscript functions may need to use the latest version, it may not be enough to put $.noConflict(); as the last line. To avoid thinking about that possibility, you can write your script like this:

...
// @require https://code.jquery.com/jquery-3.6.0.min.js
// ==/UserScript==

((jQueryAsAParameter) => {
  // use jQueryAsAParameter in here, because $ may refer to the old version
  ...
})($);

$.noConflict();

This is called an IIFE if you want to learn more. The above is kind of weird. I wrote it that way to make the next example easier to understand. This achieves the same effect, but in my opinion, it's more idiomatic.

...
// @require https://code.jquery.com/jquery-3.6.0.min.js
// ==/UserScript==

(($) => {
  ...
})($);

$.noConflict();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM