Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, No Conflict for Tampermonkey

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?

like image 466
Dan Rosenstark Avatar asked Oct 28 '25 09:10

Dan Rosenstark


2 Answers

Add this to Tampermonkey:

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

Resolving jQuery Conflicts

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.

like image 131
Dan Rosenstark Avatar answered Oct 30 '25 00:10

Dan Rosenstark


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

like image 27
charlietfl Avatar answered Oct 29 '25 23:10

charlietfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!