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?