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

JavascriptJqueryGreasemonkeyTampermonkey

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

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

inside your userscript

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

Brock's answer is good, but I'd like to offer another solution to the AJAX problem that is more modern and elegant.

Since his script, like most others, also uses setInterval() to check periodically (300ms), it can't respond instantly and there is always a delay. And other solutions uses onload events, which will often fire earlier than you want on dynamic pages.

You can use MutationObserver() to listen for DOM changes and respond to them as soon as the element is created

(new MutationObserver(check)).observe(document, {childList: true, subtree: true});

function check(changes, observer) {
	if(document.querySelector('#mySelector')) {
		observer.disconnect();
		// code
	}
}

Though since check() fires on every single DOM change, this may be slow if the DOM changes very often or your condition takes a long time to evaluate, so instead of observing document, try to limit the scope by observing a DOM subtree that's as small as possible.

This method is very general and can be applied to many situations. To respond multiple times, just don't disconnect the observer when triggered.

Another use case is if you're not looking for any specific element, but just waiting for the page to stop changing, you can combine this with a timer.

var observer = new MutationObserver(resetTimer);
var timer = setTimeout(action, 3000, observer); // wait for the page to stay still for 3 seconds
observer.observe(document, {childList: true, subtree: true});

// reset timer every time something changes
function resetTimer(changes, observer) {
	clearTimeout(timer);
	timer = setTimeout(action, 3000, observer);
}

function action(observer) {
	observer.disconnect();
	// code
}

This method is so versatile, you can listen for attribute and text changes as well. Just set attributes and characterData to true in the options

observer.observe(document, {childList: true, attributes: true, characterData: true, subtree: true});

Solution 5 - Javascript

wrapping my scripts in $(window).load(function(){ }) never failed for me.

maybe your page has finished, but there is still some ajax content being loaded.

if that is the case, this nice piece of code from Brock Adams can help you:
https://gist.github.com/raw/2625891/waitForKeyElements.js

i usually use it to monitor for elements that appears on postback.

use it like this: waitForKeyElements("elementtowaitfor", functiontocall)

Solution 6 - Javascript

If you want to manipulate nodes like getting value of nodes or changing style, you can wait for these nodes using this function

const waitFor = (...selectors) => new Promise(resolve => {
    const delay = 500
    const f = () => {
        const elements = selectors.map(selector => document.querySelector(selector))
        if (elements.every(element => element != null)) {
            resolve(elements)
        } else {
            setTimeout(f, delay)
        }
    }
    f()
})

then use promise.then

// scripts don't manipulate nodes
waitFor('video', 'div.sbg', 'div.bbg').then(([video, loading, videoPanel])=>{
    console.log(video, loading, videoPanel)
    // scripts may manipulate these nodes
})

or use async&await

//this semicolon is needed if none at end of previous line
;(async () => {
    // scripts don't manipulate nodes
    const [video, loading, videoPanel] = await waitFor('video','div.sbg','div.bbg')
    console.log(video, loading, video)
    // scripts may manipulate these nodes
})()

Here is an example icourse163_enhance

Solution 7 - Javascript

To detect if the XHR finished loading in the webpage then it triggers some function. I get this from https://stackoverflow.com/questions/43282885/how-do-i-use-javascript-to-store-xhr-finished-loading-messages-in-the-console and it real works.

    //This overwrites every XHR object's open method with a new function that adds load and error listeners to the XHR request. When the request completes or errors out, the functions have access to the method and url variables that were used with the open method.
	//You can do something more useful with method and url than simply passing them into console.log if you wish.
	//https://stackoverflow.com/questions/43282885/how-do-i-use-javascript-to-store-xhr-finished-loading-messages-in-the-console
	(function() {
		var origOpen = XMLHttpRequest.prototype.open;
		XMLHttpRequest.prototype.open = function(method, url) {
			this.addEventListener('load', function() {
				console.log('XHR finished loading', method, url);
				display();
			});

			this.addEventListener('error', function() {
				console.log('XHR errored out', method, url);
			});
			origOpen.apply(this, arguments);
		};
	})();
	function display(){
		//codes to do something;
	}

But if there're many XHRs in the page, I have no idea how to filter the definite one XHR.

Another method is waitForKeyElements() which is nice. https://gist.github.com/BrockA/2625891
There's sample for Greasemonkey use. https://stackoverflow.com/questions/11195658/run-greasemonkey-script-on-the-same-page-multiple-times/11197969#11197969

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMyne MaiView Question on Stackoverflow
Solution 1 - Javascriptdevnull69View Answer on Stackoverflow
Solution 2 - JavascriptBrock AdamsView Answer on Stackoverflow
Solution 3 - JavascriptLeviathanView Answer on Stackoverflow
Solution 4 - JavascriptgoweonView Answer on Stackoverflow
Solution 5 - JavascriptRASGView Answer on Stackoverflow
Solution 6 - JavascriptbilabilaView Answer on Stackoverflow
Solution 7 - JavascriptDave BView Answer on Stackoverflow