Using $.ajaxStop() to determine when page is finished loading in CasperJS

有些话、适合烂在心里 提交于 2020-01-05 18:01:03

问题


So far in my tests written in CasperJS, I've been using waitForSelector() on page-specific elements to determine if a page has fully loaded (including all the async ajax requests). I was hoping to come up with a more standard way of waiting for page load and was wondering if the following was possible?

  1. Inject as clientscript the following (include.js)

    $(document).ajaxStop(function() {
        // Do something
    })
    

Description of ajaxStop according to jquery api: Register a handler to be called when all Ajax requests have completed.

  1. Define a casper.waitForLoad function that when called would wait for the "something" in above code block

  2. Use the function in several parts of the test.

Also any tips on the // Do Something part would also be appreciated :) I was thinking about using the window.callPhantom feature in phantomJS but I'm reading that it's not officially supported in casperjs.


回答1:


I would do something like this in include.js:

(function(){
    window._allAjaxRequestsHaveStopped = false;
    var interval;
    $(document).ajaxStop(function() {
        if (interval) {
            clearInterval(interval);
            interval = null;
        }
        interval = setTimeout(function(){
            window._allAjaxRequestsHaveStopped = true;
        }, 500);
    });
    $(document).ajaxStart(function() {
        window._allAjaxRequestsHaveStopped = false;
        if (interval) {
            clearInterval(interval);
            interval = null;
        }
    });
})();

This sets a (hopefully unique) variable to the window object that can be later retrieved. This also waits a little longer incase there is another request after the previous batch ended.

In CasperJS you would probably do something like the following to wait for the change in the request status. This uses adds a new function to the casper object and uses casper.waitFor() internally to check the change.

casper.waitForAjaxStop = function(then, onTimeout, timeout){
    return this.waitFor(function(){
        return this.evaluate(function(){
            return window._allAjaxRequestsHaveStopped;
        });
    }, then, onTimeout, timeout);
};

And use it like this:

casper.start(url).waitForAjaxStop().then(function(){
    // do something
}).run();

or this:

casper.start(url).thenClick(selector).waitForAjaxStop().then(function(){
    // do something
}).run();


来源:https://stackoverflow.com/questions/30986078/using-ajaxstop-to-determine-when-page-is-finished-loading-in-casperjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!