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

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?


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

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

inside your userscript


This is a common problem and, as you've said, waiting for the page load is not enough -- since AJAX can and does change things long after that.

There is a standard(ish) robust utility for these situations. It's the waitForKeyElements() utility.

Use it like so:

// ==UserScript==
// @name     _Wait for delayed or AJAX page load
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a major design
    change introduced in GM 1.0.
    It restores the sandbox.
*/

waitForKeyElements ("YOUR_jQUERY_SELECTOR", actionFunction);

function actionFunction (jNode) {
    //-- DO WHAT YOU WANT TO THE TARGETED ELEMENTS HERE.
    jNode.css ("background", "yellow"); // example
}

Give exact details of your target page for a more specific example.


As of Greasemonkey 3.6 (November 20, 2015) the metadata key @run-at supports the new value document-idle. Simply put this in the metadata block of your Greasemonkey script:

// @run-at      document-idle

The documentation describes it as follows:

The script will run after the page and all resources (images, style sheets, etc.) are loaded and page scripts have run.