开发者

Greasemonkey Userscript: pasting in jQuery?

I'm develop开发者_运维问答ing a Greasemonkey script to be used only with Firefox, and I need some help. I'm planning to use jQuery, and possibly some other scripts later on. Since the @require for GM only downloads the script at the initial install, later updates to the code won't download updates to external scripts.

Therefore, i was wondering: What happens if I paste in the raw jQuery code? IE the one found here: http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js

Would it cause errors? What if the website on which the script is used uses jQuery 1.3.2 and I paste in jQuery 1.4.2 into the page, or vice-versa? Basically, what are the disadvantages or errors caused if I paste in the full source for scripts like jQuery, jQuery UI etc?

Thanks!


I've done this before - one long jQuery line near the top. It's not elegant, but it works fine for the time being, and works as expected. Variables in your Greasemonkey script do not affect the webpage itself, unless you explicitly access the webpage's scope via unsafeWindow.

It was a while ago, however, and I believe jQuery 1.4 does not work with this method anymore. If using 1.3 is an option, try that, instead.


For GM, each script is executed in it's own scope, so if you use @require, or paste a library (like jQuery) directly into your userscript (which is effectively equivalent), then this won't effect the scripts loaded by the page. So it won't matter if the page has jQuery loaded already, you can still load any version into your userscript. There are some versions of jQuery that don't work in a userscript however, and sometimes people recommend changing a window variable reference to unsafeWindow in order to get jQuery to work, if you do this then everything I just said goes out the window, because the unsafeWindow scope is where the page's scripts are loaded, so playing with that means you are leaving the userscript's scope.

So if you want to use jQuery, then find a version that can be @require'd (I think 1.3.2 may work) without requiring you to use unsafeWindow.

If you must use unsafeWindow, then do the following:

// check that jQuery is not already loaded
if (!unsafeWindow.$) {
  // paste jQuery code here..
}


Your code inclusion will most likely overwrite the version of jQuery on the page. Not a big deal in most cases, though jQuery 1.4 deprecated some functionality of the previous versions that may break JavaScript already on the site. Most notable is that pre-1.4, $() returned the document, it now returns an empty jQuery object.

I think the best way to do it would be to see if jQuery is already loaded, that is check to see if the jQuery object exists, and then check if the function you need to use exists (if it is a function new to 1.4). If not, then include the code from Google cache or wherever. You can make an AJAX request and execute the returned script.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜