---
title: "jQuery & Greasemonkey"
author: "Pweb"
date: "2010-08-28T15:01:08Z"
tags: []
categories: ["Web前端"]
slug: "jquery-greasemonkey"
draft: false
lastmod: "2010-08-28T15:03:12Z"
id: 749679
url: "https://pwb.iteye.com/blog/749679"
---

## How to play nicely with jQuery and Greasemonkey

![jQuery & Greasemonkey](http://joanpiedra.com/jquery/greasemonkey/images/pic.png "jQuery & Greasemonkey")

* * *

## Overview

This is a simple snippet that helps us load the jQuery power into our userscripts with Greasemonkey 0.7 or lower, newer versions may use [@require](http://wiki.greasespot.net/Third-Party_Libraries) .

* * *

## Updates

**2010-04-24:**  
The userscript checks if jQuery is already loaded in the page and uses it, otherwise loads it from Google's CDN. It's also using jQuery.noConflict(true).

Thanks to everyone who sent me emails about this over this and last year.

* * *

## Code

javascript:

var $;

// Add jQuery  
(function(){  
if (typeof unsafeWindow.jQuery == 'undefined') {  
var GM\_Head = document.getElementsByTagName('head')\[0] || document.documentElement,  
GM\_JQ = document.createElement('script');

GM\_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';  
GM\_JQ.type = 'text/javascript';  
GM\_JQ.async = true;

GM\_Head.insertBefore(GM\_JQ, GM\_Head.firstChild);  
}  
GM\_wait();  
})();

// Check if jQuery's loaded  
function GM\_wait() {  
if (typeof unsafeWindow.jQuery == 'undefined') {  
window.setTimeout(GM\_wait, 100);  
} else {  
$ = unsafeWindow.jQuery.noConflict(true);  
letsJQuery();  
}  
}

// All your GM code must be inside this function  
function letsJQuery() {  
alert($); // check if the dollar (jquery) function works  
alert($().jquery); // check jQuery version  
}