PhantomJS: wait for it

When you want to take screenshots with PhantomJS, you probably need to wait before your page is completely loaded. I mean all resources are loaded and scripts executed.

Use the following code to delay your screenshot :

var page = new WebPage();
page.open('http://stackoverflow.com/', function (status) {
        just_wait();
});

function just_wait() {
    setTimeout(function() {
            page.render('screenshot.png');
            phantom.exit();
    }, 2000);
}

Here we wait 2000ms before saving the screenshot. Adjust it to fit your needs.

Edit 2016-08-31

Since phantomjs 1.2, you can use the callback onLoadFinished()¬†which is much better than a simple guess on the rendering time…

 

var page = new WebPage();
page.open('http://charles.lescampeurs.org/');
page.onLoadFinished = function(status) {
    page.render('screenshot.png');
    phantom.exit();
};

 

 
  • Luke

    and how do you know it will be rendered within 2 seconds, always?

    http://phantomjs.org/api/webpage/handler/on-load-finished.html

  • Charles

    You’re right, that’s was just a guess… You’re right, it’s better to use the hook onLoadFinished()

  • Rob

    onLoadFinished does not work properly for me. The blind timeout works great though.