User Script Tip: Using jQuery

A very common question that I see asked on stackoverflow.com, the greasemonkey-users mailing list, and in #greasemonkey on freenode, is how to use third party libraries with a user script.

The common response is to use @require, but these days people want their user scripts to work on Google Chrome too, and unfortunately Google Chrome user scripts do not support a lot of the Greasemonkey metadata block, including @require.. so another method is required.

Cross Browser Solutions

Use script element & setTimeouts

One method that has been mentioned elsewhere is to create a script element and add it to the page, and use setTimeout's to wait until the third party js, in this example jQuery, is loaded. The example in the link I provided is for Greasemonkey, but with little effort it can be made to work with Google Chrome.

Use script element & associated onload event

This method creates script element for jQuery (or some other third party script), and appends it to the body element, and listens to the load event to figure out when the library is loaded and ready to be used.

Google Chrome does not allow user scripts to access javascript objects in the page scope from the user script's scope, so in order to use jQuery at all on Google Chrome you must load jQuery into the page scope and inject your script into the page scope. So this is what my example below does essentially, more specifically it stringifys a callback function which is called when jQuery is done loading.

Example

© Erik Vold 2007-2010. Contact Erik Vold. Top ^