如何检测phantomjs何时完成渲染?

时间:2013-07-30 18:13:43

标签: phantomjs rasterizing

我正在使用phantomjs将几个专门的html页面呈现为PDF;因为这是一项需要扩展的服务,所以我试图减少尽可能多的开销。所有页面都是相同的结构,使用相同的CSS,并且在大多数方面类似,所以我决定重用相同的html页面,只需调用javascript来替换内容。这样就无需重新加载CSS和Web字体等。

为了使事情稍微复杂一点,我使用我使用phantom.js的webserver接口创建的rest接口来控制来自node.js的渲染。 Web服务器运行良好 - 如果我不重用页面,一切都运行良好。

我遇到的问题是我无法知道何时可以向节点(通过http连接)报告该文件已准备好使用。

if (filename.substr(-4) == ".pdf") {
    p.paperSize = {format: 'Letter', orientation: 'portrait', margin: '1cm'};
}
// loadPage evaluates javascript in the page to have it load the contents
// of the url into its body; the callback is triggered by a console.log
// inside the page that tells us when the ajax request has finished and
// the content is ready to be rendered.
loadPage(p, url, function() {
    console.log("Loaded", url);
    p.render(filename);
    console.log("Rendered?", url);
    // sendJSON returns the response to the node client
    sendJSON(response, {filename: filename, status: "success"});
});

我遇到的问题是在p.render完成之前调用sendJSON - 它没有阻塞。老实说,我不认为它是阻塞的,因为这是javascript,但它似乎也不接受回调函数让我知道它什么时候完成。

有人找到了解决这类问题的方法吗?

1 个答案:

答案 0 :(得分:1)

事实证明它实际上是在渲染上阻塞,但它似乎并不是因为在调用渲染时页面本身仍在加载。 $(window).load本身做得不够,以确保在响应之前加载了css和字体以及所有内容。

对于任何想要尝试这样的事情的人来说,它似乎比每次创建一个新页面要快一点,但是让时机都正确可能有点棘手。

相关问题