DOMContentLoaded and Greasemonkey

A very common purpose of Greasemonkey scripts is modifying the DOM structure of the document, mostly adding something new.

I’ve written several scripts before and have been doing such modifications in the “load” event handler, as in this script. The problem is that “load” event is fired after all images on the page have been downloaded completely, so users may suffer a great delay to see the changes occur if there’re many images.

jQuery users know that jQuery has a function “ready”. It won’t wait for the images to load. We are writing Greasemonkey scripts, so we only care about Firefox. Firefox has a “DOMContentLoaded” event explained in detail here.

Fired on a Window object when a document’s DOM content is finished loaded, but unlike “load”, does not wait till all images are loaded. Used for example by GreaseMonkey to sneak in to alter pages before they are displayed.

So when writing my last script I tried to rely on this event:

window.addEventListener('DOMContentLoaded', function(e) {
	...
}, false);

But the codes in the handler were not executed.

I was confused and did some searching. Finally I got this page saying that “the code in a Greasemonkey user script gets invoked when the DOMContentLoaded event fires”. That explains all. The “DOMContentLoaded” event was already fired so the codes never had a chance to get executed.

The solution, of course, is pulling the handler codes out of the wrapper. If your script doesn’t really rely on the “load” event, don’t put them into its handler because there may be a obvious delay.

3 Replies to “DOMContentLoaded and Greasemonkey”

  1. Please be more specific. What do you mean by “pulling the handler codes out of the wrapper”? Are you referring to using unsafeWindow? If not, what wrapper, and what handler codes? I’m trying to figure out how to get Greasemonkey working BEFORE DOMContentLoaded.

Leave a Reply

Your email address will not be published. Required fields are marked *

Prove your intelligence before hitting * Time limit is exhausted. Please reload CAPTCHA.