代码之家  ›  专栏  ›  技术社区  ›  Dan7

在greasemonkey中使用jquery 1.4,而原始页面使用jquery 1.3(不同版本)?

  •  3
  • Dan7  · 技术社区  · 16 年前

    在用户脚本中提供必要的新版本jquery(1.4.2)的最佳策略是什么?该脚本将修改已经具有旧版本jquery(1.3.1)的页面?

    最好原始页面继续使用“$”符号,而在我的脚本中,它使用的别名由 jquery.noConflict() .

    根据答案 this question ,任何希望加载的额外版本都应放在原始脚本标记的上方。这就是我有点困惑的地方,因为我觉得Greasemonkey在页面加载后执行脚本?

    编辑: 一个想法是在用户脚本中,为jquery 1.4.2附加一个脚本标记,设置别名,然后再次为1.3.1附加一个脚本标记,以免破坏使用1.3.1函数的原始页面代码。

    var code142 = function() {
        gj = jQuery.noConflict(true);
        alert("142...");
        alert(gj); // check if the dollar (jquery) function works
        alert(gj().jquery); // check jQuery version
    }
    
    var script = document.createElement("script");
    script.src = 'http://code.jquery.com/jquery-1.4.2.min.js'
    document.documentElement.appendChild(script);
    
    
    // assign jquery object alias and run code that uses 1.4.2 there
    var script = document.createElement("script");
    script.textContent = '(' + code142.toString() + ')();';
    document.documentElement.appendChild(script);
    
    /* The following is perhaps redundant, see EDIT 2 for more info
    
    // add jquery 1.3.1 (again)
    var script = document.createElement("script");
    script.src = 'http://code.jquery.com/jquery-1.3.1.min.js'
    document.documentElement.appendChild(script);
    
    */
    

    但这将要求每页加载jquery库3次。有更好的方法吗?

    编辑2: 虽然gm脚本提供了一个1.4.2副本,但是原始页面似乎仍然可以使用它的1.3.1副本,只要我使用新的别名,它们就可以共存。( gj )在内部引用1.4.2 jquery对象 code142() .

    如果没有别的事情发生,这就是我的解决办法。我希望它对其他可能遇到这个问题的人有用。

    1 回复  |  直到 16 年前
        1
  •  2
  •   Nick Craver    16 年前

    I believe this is what you're looking for .

    只要您不做任何复杂的事情,并且不需要最新版本,就按照链接中的模式来包含它。

    它检查是否加载了jquery( typeof unsafeWindow.jQuery == 'undefined' )在再次包括之前。“简单”部分只意味着你在1.3和1.4中,可能是1.2.6中所做的工作会是这样吗?如果是这样的话,不管你加载哪个版本,只要它被加载。(除非是A 非常 老遗址 check that the functions you're using so way back in jQuery core ,但这种可能性要小得多)

    推荐文章