How to wait for page loading when using casperjs? How to wait for page loading when using casperjs? javascript javascript

How to wait for page loading when using casperjs?


I've been using the waitForSelector 'workaround' mentioned by Arun here:https://stackoverflow.com/a/22217657/1842033

It's the best solution I've found; the 'drawback' as it were is that you need to be aware of what element you're expecting to load. I say drawback, personally I don't think I've encountered a situation where I've not had some kind of feedback saying that whatever I'm waiting for has happened

this.waitForSelector("{myElement}",    function pass () {        test.pass("Found {myElement}");    },    function fail () {        test.fail("Did not load element {myElement}");    },    20000 // timeout limit in milliseconds);

Although I'd guess you could use waitForResource() or something like that if you didn't have visual feedback.


What I've taken to doing to get around this issue, when there isn't anything specific to target and wait for in the reloaded page, is to use the following:

var classname = 'reload-' + (new Date().getTime()),    callback = function(){},    timeout = function(){};/// It happens when they change something...casper.evaluate(function(classname){  document.body.className += ' ' + classname;}, classname);casper.thenClick('#submit'); /// <-- will trigger a reload of the pagecasper.waitWhileSelector('body.' + classname, callback, timeout);

This way I don't have to rely on a specific expected element in the next page, I've basically done the inverse. I've created a specific selector to watch out for, and execution moves on once that selector fails to match.

For my intents and purposes it was enough to know the page had begun reloading, I didn't need to wait until the next page had fully reloaded. This is so that I could then trigger certain waitForSelector calls on elements that may have existed both before and after the reload. Waiting until the temporary class has been removed lets me know that anything that existed before has since been destroyed, so no fear of selecting elements prior to the reload.


Seems there are no real solutions.http://docs.casperjs.org/en/latest/modules/casper.html#waitforselector is an available workaround which may not work always.