1

I am writing a userscript to run on a site that I know already includes the jQuery libraries. So, on my first attempt, I just called jQuery functions directly in the userscript—for example:

$('.some-class').css('color', 'red');

or whatever. This worked just fine (using Tampermonkey and Greasemonkey, where I tested it).

But I was looking at some other people's code, and I saw that they made their own copy of jQuery at the top of the userscript. Something like:

var $, jQuery;
$ = jQuery = window.jQuery;

What is the purpose of this? It doesn't seem to be required in order to have access to jQuery inside of the userscript, so why do people do it?

In researching this, I found an answer by hheimbuerger that recommends doing the same thing:

If you want to use jQuery on a site where it is already included, this is the way to go (inspired by BrunoLM):

var $ = unsafeWindow.jQuery;

but the answer doesn't explain why this is recommended. Can someone explain the logic behind this and what purpose it serves? What will go wrong if I don't do it? Will my userscript break in other browsers? Am I setting myself up for some kind of security risks?

Katie
  • 51
  • 7
  • I would guess it's so you know exactly what version of jQuery is being used. I'd suggest assigning it to another variable than `$` using `noConflict()` though, otherwise you may end up breaking the site. – Rory McCrossan Oct 13 '17 at 13:19
  • Because it is possible to sandbox the user script so it is isolated from window name space – charlietfl Oct 13 '17 at 13:20
  • Also note that a *"reference"* and *"copy"* are not the same thing. You are not copying anything – charlietfl Oct 13 '17 at 13:25
  • @Katie, I'd also go with `var $ = unsafeWindow.jQuery;` as `window.$` may be overwritten by some script on the page. See any discussion about `jQuery.noConflict()`. That's why I'd store the reference to the real thing `unsafeWindow.jQuery` in a local variable `$`; to ensure that **in my code** always `$ === jQuery` – Thomas Oct 13 '17 at 13:34

0 Answers0