如何用Google PageSpeed API计算网页总大小?

How to calculate total size of webpage with Google PageSpeed API?

"statistics": {
    "cssResponseBytes": "333 kB",
    "htmlResponseBytes": "269 kB",
    "imageResponseBytes": "3.35 MB",
    "javascriptResponseBytes": "2.29 MB",
    "numberCssResources": 2,
    "numberHosts": 80,
    "numberJsResources": 72,
    "numberResources": 237,
    "numberStaticResources": 50,
    "otherResponseBytes": "53.1 kB",
    "textResponseBytes": "160 kB",
    "totalRequestBytes": "69.7 kB"
  },

这是我从 Google PageSpeed API 获取页面统计信息的 JSON 响应。如果可能的话,我如何计算加载页面的整个下载大小?我的假设是将响应中的前 4 行加在一起(responsebytes)

您可以创建一个函数来解析结果并计算总字节数,例如

var obj = {
    "statistics": {
        "cssResponseBytes": "333 kB",
        "htmlResponseBytes": "269 kB",
        "imageResponseBytes": "3.35 MB",
        "javascriptResponseBytes": "2.29 MB",
        "numberCssResources": 2,
        "numberHosts": 80,
        "numberJsResources": 72,
        "numberResources": 237,
        "numberStaticResources": 50,
        "otherResponseBytes": "53.1 kB",
        "textResponseBytes": "160 kB",
        "totalRequestBytes": "69.7 kB"
      }
}

var result = Object.keys(obj.statistics)
           .filter( k => k.includes('ResponseBytes'))
                   .map( v => {
             var calc = {kB:1,MB:1024,GB:1048576}; // etc
                 var size = +obj.statistics[v].replace(/\s.+$/,'');
                        var mult = obj.statistics[v].split(/\s/).pop();
                        return size * (calc[mult]||0);
                    }).reduce( (a,b) => a+b).toFixed(2) + ' kB';
                   
console.log(result)