如何测量 PhantomJS 中的渲染时间?

How to measure the rendering time in PhantomJS?

据我所知,PhantomJS 在调用 page.open 时开始加载页面。 首先,它加载页面资源,然后呈现页面,然后调用 open 回调。

现在我只想知道渲染时间(也就是说,没有资源加载时间)。我可以这样做吗?

Phantom js 使用 webkit 引擎..所以它的行为将类似于 chrome。 网页呈现在收到第一个资源后立即开始。它不像它会等待所有资源到达。 估计渲染时间的一种简单技术是在本地拥有资源,这样网络延迟就会最小。并使用这样的脚本获取加载时间。

t = Date.now();
page.open(address, function(status) {
    if (status !== 'success') {
        console.log('FAIL to load the address');
    } else {
        t = Date.now() - t;
        console.log('Loading ' + address);
        console.log('Loading time ' + t + ' msec');
    }
    phantom.exit();
});

无论如何,这不会是准确的并且总是可行的。
因此,另一种技术是计算在最后一个资源到达后准备好页面所花费的时间。(不需要进一步的网络请求)。如果某些脚本或资源有问题,这将给出估计。

var  t = Date.now();
page.onResourceReceived = function(response) {
    if(Date.now() > t)
    {
        t = Date.now();
    }
};

page.open(address, function(status) {
    if (status !== 'success') {
        console.log('FAIL to load the address');
    }
    else 
    {
        t = Date.now() - t;
        console.log('Loading ' + address);
        console.log('Rendering time' + t + ' msec');
    }
    phantom.exit();
});

当我考虑 渲染时间 时,我会考虑从已经建立的 DOM 和 CSSDOM 生成图像。我不认为您可以从脚本访问它,但您可以通过 window.performance.timing 访问 PerformanceTiming 对象。它有多个时间表示各种网络和 JavaScript 执行事件。

最接近您的情况的指标是

console.log(page.evaluate(function(){
    var t = performance.timing;
    return t.domContentLoadedEventEnd - t.domContentLoadedEventStart;
}));

请注意,PerformanceTiming 仅在 PhantomJS 2 之后可用。

这是一个打印可用数字并理解它们的小脚本:

console.log(JSON.stringify(page.evaluate(function(){
    function cloneObject(obj) {
        var clone = {};
        for(var i in obj) {
            if(typeof(obj[i])=="object" && obj[i] != null)
                clone[i] = cloneObject(obj[i]);
            else
                clone[i] = obj[i];
        }
        return clone;
    }
    return cloneObject(window.performance);
}), undefined, 4));

为 whosebug.com 打印以下内容:

{
    "navigation": {
        "TYPE_BACK_FORWARD": 2,
        "TYPE_NAVIGATE": 0,
        "TYPE_RELOAD": 1,
        "TYPE_RESERVED": 255,
        "redirectCount": 0,
        "type": 0
    },
    "now": {},
    "timing": {
        "connectEnd": 1450633550342,
        "connectStart": 1450633550342,
        "domComplete": 0,
        "domContentLoadedEventEnd": 1450633551673,
        "domContentLoadedEventStart": 1450633551657,
        "domInteractive": 1450633551657,
        "domLoading": 1450633550818,
        "domainLookupEnd": 1450633550342,
        "domainLookupStart": 1450633550342,
        "fetchStart": 1450633550342,
        "loadEventEnd": 0,
        "loadEventStart": 0,
        "navigationStart": 1450633550342,
        "redirectEnd": 0,
        "redirectStart": 0,
        "requestStart": 1450633550342,
        "responseEnd": 1450633550934,
        "responseStart": 1450633550342,
        "secureConnectionStart": 0,
        "unloadEventEnd": 0,
        "unloadEventStart": 0
    }
}