Dan Rosenstark Dan Rosenstark - 4 months ago 44
jQuery Question

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?

Answer

Use a load handler on new script tag

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

DEMO