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

前端 未结 7 1990
迷失自我
迷失自我 2020-11-27 10:24

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 displ

7条回答
  •  独厮守ぢ
    2020-11-27 11:13

    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.

提交回复
热议问题