Userscript在执行代码技术之前等待页面加载?

时间:2012-10-15 14:09:03

标签: javascript jquery greasemonkey tampermonkey

我正在编写一个Greasemonkey用户脚本,并希望在页面完全加载时执行特定代码,因为它返回了我想要显示的div计数。

问题是,在加载所有内容之前,这个特定页面有时需要一点点。

我已经尝试过,记录$(function() { });$(window).load(function(){ });包装器。但是,似乎没有一个对我有用,尽管我可能会错误地应用它们。

我能做的最好的事情是使用一个有效的setTimeout(function() { }, 600);,虽然它并不总是可靠的。

在Greasemonkey中使用哪种最佳技术来确保在页面加载完成后执行特定代码?

7 个答案:

答案 0 :(得分:55)

Greasemonkey(通常)没有jQuery。所以常见的方法是使用

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

在您的用户名

答案 1 :(得分:46)

这是一个常见的问题,正如您所说,等待页面加载是不够的 - 因为AJAX可以并且确实在此之后很久就改变了。

这些情况有一个标准(ish)强大的实用程序。这是the waitForKeyElements() utility

像这样使用它:

// ==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
}

提供目标网页的确切详细信息,以获取更具体的示例。

答案 2 :(得分:23)

自Greasemonkey 3。6(2015年11月20日)起,元数据键@run-at支持新值document-idle。 只需将它放在Greasemonkey脚本的元数据块中:

// @run-at      document-idle

documentation描述如下:

  

脚本将在页面和所有资源(图像,样式表等)加载并运行页面脚本之后运行。

答案 3 :(得分:10)

将我的脚本包裹在$(window).load(function(){ })中从未对我失败。

也许您的页面已经完成,但仍然会加载一些ajax内容。

如果是这种情况,来自Brock Adams的这段优秀代码可以帮助您:
https://gist.github.com/raw/2625891/waitForKeyElements.js

我通常用它来监控回发上显示的元素。

像这样使用它:waitForKeyElements("elementtowaitfor", functiontocall)

答案 4 :(得分:3)

如果您想操纵节点的值,比如获取节点值或更改样式,可以使用此函数等待这些节点

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

然后使用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
})

或使用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
})()

以下是icourse163_enhance

的示例

答案 5 :(得分:2)

Brock's answer很好,但我想为AJAX问题提供另一种解决方案,以确保完整性。由于他的脚本也使用setInterval()定期检查(300毫秒),因此无法立即响应。

如果您需要立即回复,可以使用MutationObserver()侦听DOM更改,并在创建元素后立即对其进行响应

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

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

虽然check()因为每个DOM更改都会触发,但如果DOM经常更改或者您的条件需要很长时间来评估,这可能会很慢。

另一个用例是,如果您没有查找任何特定元素,只是等待页面停止更改。您可以将其与setTimeout()结合使用以等待它。

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

function resetTimer(changes, observer) {
    clearTimeout(timer);
    timer = setTimeout(action, 3000, observer);
}

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

此方法非常通用,您也可以监听属性和文本更改。只需在选项

中将attributescharacterData设置为true即可
observer.observe(document, {childList: true, attributes: true, characterData: true, subtree: true});

答案 6 :(得分:1)

为了检测XHR是否在网页中完成加载,它会触发一些功能。 我从How do I use JavaScript to store "XHR finished loading" messages in the console in Chrome?得到了这个,它确实有效。

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

但如果页面中有很多XHR,我不知道如何过滤明确的XHR。

另一种方法是waitForKeyElements(),这很好。 https://gist.github.com/BrockA/2625891
有Greasemonkey使用的样本。 Run Greasemonkey script on the same page, multiple times?

相关问题