假设我有一个脚本在PhantomJS中加载网页。
var page = require('webpage').create()
var url = 'http://localhost:3000/hello.html'
page.open(url, function (status) {
var content = page.content;
console.log(content);
phantom.exit();
});
我想知道加载页面资源需要多长时间。所以我修改了我的脚本:
var page = require('webpage').create()
var dict = {}
page.onResourceRequested = function (req) {
dict[req.url] = new Date().getTime()
};
page.onResourceReceived = function (res) {
if (res.stage == "end") {
dict[res.url] = new Date().getTime() - dict[res.url];
}
};
var url = 'http://localhost:3000/hello.html'
page.open(url, function (status) {
var content = page.content;
console.log(JSON.stringify(dict))
phantom.exit();
});
有没有更好的方法来衡量请求时间?
答案 0 :(得分:2)
您测量时间的方式非常好,但资源并不总是具有唯一的URL。多个资源可以具有相同的URL,这会在您的情况下产生错误的结果。您应该使用请求的id
属性:
page.onResourceRequested = function (req) {
dict[req.id] = new Date().getTime()
};
page.onResourceReceived = function (res) {
if (res.stage == "end") {
dict[res.id] = new Date().getTime() - dict[res.id];
}
};
请注意netsniff.js中有examples directory脚本,它已经为您做了很多事情。