Myne Mai
Myne Mai

Reputation: 1505

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?

Upvotes: 145

Views: 157559

Answers (8)

a55
a55

Reputation: 556

If you dont want to load lot of codes via an external resource
There is some one-liner solutions:

var I=setInterval(()=>{if(typeof $=="function"){clearInterval(I); $(); }},200);

Or another short way

var I=setInterval(()=>{try{ XYZ();clearInterval(I); }catch{}},200);

Also you can pass some arguments

var I=setInterval(
    (a1,a2)=>{
        try{
            XYZ(a1,a2);
            clearInterval(I);
        }catch{}
    },
    200, // checks every 0.2 seconds
    arg1, arg2
);



Or use window.onload=function(){ }; instead $(window).load(function(){ });

Upvotes: 0

Brock Adams
Brock Adams

Reputation: 93473

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  https://raw.githubusercontent.com/CoeJoder/waitForKeyElements.js/refs/heads/master/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.

    If in Tampermonkey, use "// @unwrap" to enable sandbox instead.
*/

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.

Upvotes: 87

goweon
goweon

Reputation: 1354

I'd like to offer another solution to the AJAX problem that is more modern and elegant.

Brock's script, like most solutions, are using setInterval() or setTimeout() at the core to check for elements periodically, so they can't respond instantly and there is always some delay. Other solutions uses onload events, which will often fire earlier than you want on dynamic pages.

The solution: Use MutationObserver() to directly listen for DOM changes to respond immediately after an element is inserted

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

function check(changes, observer) {
    if(document.querySelector('#mySelector')) {
        observer.disconnect();
        // actions to perform after #mySelector is found
    }
}

The check function fires immediately after every DOM change. This allows you to specify arbitrary trigger conditions so you can wait until the page is in the exact state required before you execute your own code.

Note that, 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 idle timer that gets reset when the page changes.

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
}

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});

And if you want to use it in an async/await paradigm, you can do something like

function wait_element(root, selector) {
  return new Promise((resolve, reject) => {
    (new MutationObserver(check)).observe(root, {childList: true, subtree: true});
    function check(changes, observer) {
      let element = root.querySelector(selector);
      if(element) {
        observer.disconnect();
        resolve(element);
      }
    }
  });
}

let node = await wait_element(document, '#mySelector');

Upvotes: 77

Dave B
Dave B

Reputation: 69

To detect if the XHR finished loading in the webpage then it triggers some function. I get this from How do I use JavaScript to store "XHR finished loading" messages in the console in Chrome? 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. Run Greasemonkey script on the same page, multiple times?

Upvotes: 3

bilabila
bilabila

Reputation: 1163

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

Upvotes: 9

tyg
tyg

Reputation: 14966

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.

Upvotes: 64

yodog
yodog

Reputation: 6232

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)

Upvotes: 18

devnull69
devnull69

Reputation: 16544

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

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

inside your userscript

Upvotes: 120

Related Questions