【问题标题】:In a userscript/greasemonkey, how do you use a newer version of jQuery when the website already uses an older version?在用户脚本/greasemonkey 中,当网站已经使用旧版本时,如何使用新版本的 jQuery?
【发布时间】:2022-07-02 01:07:57
【问题描述】:

我正在尝试为已经使用旧版 jQuery 的网站编写用户脚本。如果我 @require 用户脚本中的现代版本,我会收到一个控制台错误,说明名为 exists 的字段不存在。由于这两个版本的 jQuery 不兼容,有什么方法可以同时使用它们而不冲突?

【问题讨论】:

    标签: javascript jquery greasemonkey tampermonkey userscripts


    【解决方案1】:

    也许有比这更好的解决方案,但这是我想出的:@require jQuery 就像你通常想要的那样,然后在你的脚本末尾加上一个 $.noConflict();。由于您的某些用户脚本功能可能需要使用最新版本,因此将$.noConflict(); 作为最后一行可能还不够。为避免考虑这种可能性,您可以这样编写脚本:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 2011-11-18
      相关资源
      最近更新 更多