views:

1302

answers:

3

Say you wanted a Greasemonkey script to be compatible with Safari and Chrome.

Whereas in Firefox the Greasemonkey scripts only run when the DOM is ready. Chrome, Safari and Opera seem to run the Greasemonkey scripts before the DOM is ready.

So what I am looking for is a solution that will only run a listener on the page, waiting for the DOM loaded/ready event, and on receiving that event, then run the rest of the script. If the browser they are using is Chrome, Safari or Opera. If they are using Firefox, just run the script straight away and not bother with the event listener.

How to code this?

@NV

Thanks NV, do you know if that script is also Google Chrome compatible?

Will the code

(function(){

    // Code here run after 'load' event in all browsers.

})();

also run on DOM ready in Google Chrome?

A: 

I suppose you might look at how JavaScript libraries like JQuery pull this off. It would probably be too heavy weight to actually use one, but they've certainly solved this problem already.

dacc
+1  A: 

First of all, take a look at Nice alert UserJS. It works on Greasemonkey, Opera, and Safari Greasekit.

If you want to run some code after page load, event listeners not necessary at all.

... safari + opera, seem to run the gm scripts before the dom is ready.

No. Actually, it's more complicated. Opera has greasemokey compatible mode. All scripts named yada-yada.user.js run in compatible mode, and run after DOM is ready.

NOTE: wrap your code into anonymous function to prevent variable leakage into global window object (this happens in Opera).

(function(){

  // Some code

})();

Safari Greasekit works like Firefox Greasemonkey in this case.

NV
Simply wrapping code in an anonymous function does NOT delay execution until after the load event. The first part of the answer above is thus wrong and misleading.
hallvors
hallvors, you are right! Maybe I'm not speaking clearly. I've updated answer.
NV
I marked answer as community wiki. So, you can edit.
NV
A: 

I took the minified jQuery and copy pasted it into my userscript, and then did the classic

  $(document).ready(function() {
      // Put all your jQuery goodness in here.
  });

Which has the added bonus of giving you jQuery, all encased in the function mentioned in another question:

(function(){

  // Some code.

})();

You could use the Greasemonkey stuff to import jQuery via URL at the top, but this is Greasemonkey specific, Chrome/Opera, etc. will not be compatible if you do it this way.

Tom J Nowell