在Userscript/GreaseMonKey中,当网站已经使用旧版本时,如何使用较新版本的jQuery?

发布于 2025-02-12 05:41:57 字数 148 浏览 1 评论 0 原文

我正在尝试为已经使用古代jQuery的网站编写一个用户订阅。如果我 @require 在用户标题中的现代版本,我会发现有关如何存在的字段不存在的控制台错误。由于这两个版本的jQuery不兼容,是否有任何方法可以使用它们而不会冲突?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深爱不及久伴 2025-02-19 05:41:57

也许有一个更好的解决方案,但这是我想到的: @require 按照您通常想要的方式,然后在脚本结束时,放置一个 $。noconflict(); 。由于您的某些Userscript功能可能需要使用最新版本,因此将作为最后一行。为了避免考虑这种可能性,您可以像这样编写脚本:

...
// @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();

这称为 iife 如果您想了解更多。以上有点奇怪。我这样写了它,使下一个示例更容易理解。这产生了相同的效果,但我认为这更惯用。

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

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

$.noConflict();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文