Userscript to wait for page to load before executing code techniques?

Myne Mai picture Myne Mai · Oct 15, 2012 · Viewed 79.5k times · Source

I'm writing a Greasemonkey user script, and want the specific code to execute when the page completely finishes loading since it returns a div count that I want to be displayed.

The problem is, that this particular page sometimes takes a bit before everything loads.

I've tried, document $(function() { }); and $(window).load(function(){ }); wrappers. However, none seem to work for me, though I might be applying them wrong.

Best I can do is use a setTimeout(function() { }, 600); which works, although it's not always reliable.

What is the best technique to use in Greasemonkey to ensure that the specific code will execute when the page finishes loading?

Answer

devnull69 picture devnull69 · Oct 15, 2012

Greasemonkey (usually) doesn't have jQuery. So the common approach is to use

window.addEventListener('load', function() {
    // your code here
}, false);

inside your userscript