jQuery,Tampermonkey 没有冲突

jQuery, No Conflict for Tampermonkey

我正在为一个使用旧版本 jQuery 的站点使用 Tampermonkey 脚本。我想在我的脚本中使用更新的版本。我试过这个:

var contentIndex = 0;
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var jQuery_310 = $.noConflict(true);

但是 noConflict 运行晚了(看起来):我正在篡改的站点现在正在与较新的 jQuery.

通信

如何避免现有网站上的这种冲突?

在新脚本标签上使用加载处理程序

var jQuery_310; 
script.onload = function() {
  jQuery_310 = $.noConflict(true);
  console.log("$ calls: " + $.fn.jquery + ", jQuery_310 calls: " + jQuery_310.fn.jquery);
  // initialize any code that uses jQuery_310 here
  init_jQuery_310_code(jQuery_310);
}

function init_jQuery_310_code($) {
  console.log("here in init_jQuery_310_code: $ calls: " + $.fn.jquery);     
  // "$" refers to jQuery_310 version here
  // insert code that requires jQuery_310 here, but use "$" instead
}

DEMO

将此添加到 Tampermonkey:

// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js
// @grant        none

解决jQuery 冲突

主站点对 $ 的使用将引用新的 jQuery (310),这可能会破坏 "tampered" 站点上的内容。要解决这个问题,第一行代码可以是:

window.jQuery310 = $.noConflict(true);

另一种选择: A more restrictive @grant 将不需要 noConflict 行。