I'm toying with a Tampermonkey script for a site that uses an old version of jQuery. I would like to use a more recent version in my script. I have tried this:
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);
but the noConflict runs late (it seems): the site I'm tampering with is now talking to the newer jQuery.
How can I avoid this conflict on the existing site?
Add this to Tampermonkey:
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js
// @grant        none
The main site's use of $ would refer to the new jQuery (310), which might break things on the "tampered" site. To resolve this, the first line of code could be:
window.jQuery310 = $.noConflict(true);
Another option: A more restrictive @grant would obviate the need for the noConflict line.
Use a load handler on new script tag
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With