How to use jQuery 1.4 (safely) in a Firefox add-on

July 22, 2010

jQuery and Firefox, you’d think it would be easy, but no.

The main problem here is if you include jQuery like you would any other javascript file then you’ll notice that toolbar buttons will dissapear and other layout problems will occur. It’ll also cause havoc for any other add-on that has jQuery included in it (because all add-on inhabit the same global namespace).

So what we need is a safe way to load jQuery, that wont cause rendering errors, and won’t cause conflicts with other extensions.

Firstly the rendering problem can be solved by waiting for the browser to load before loading jquery


window.addEventListener("load", function jQueryLoader(evt){
	window.removeEventListener("load", jQueryLoader, false);

	//load jQuery
	Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
		.getService(Components.interfaces.mozIJSSubScriptLoader)
		.loadSubScript("chrome://lazarus/content/js/jquery.1.4.2.js"); 

}, false);

And now to avoid the conflicts with other addons by wrapping our loader in a closure

//wrap our code in a closure so it doesn't conflict with other add-ons
(function(){
	window.addEventListener("load", function jQueryLoader(evt){
		window.removeEventListener("load", jQueryLoader, false);

		//load jQuery
		Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
			.getService(Components.interfaces.mozIJSSubScriptLoader)
			.loadSubScript("chrome://lazarus/content/js/jquery.1.4.2.js"); 

		//copy the jQuery variable into our namespace
		var $ = window.$;

		//then restore the global $ and jQuery objects
		jQuery.noConflict(true);

		//a couple of tests to make verify
		//alert(window.$);
		//alert(window.jQuery);
		//alert($);

		//now do something cool with it
		$('#appcontent').hide();

	}, false);
})();

Comments are closed.