Search code examples
javascriptjsonwebpagespeed

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"
  },

This is the JSON response im getting for the statistics of a page from the Google PageSpeed API. How can I calculate the entire download size of loading the page with this, if possible? My assumption is to ADD the first 4 lines in the response together (responsebytes)


Solution

  • You can create a function that parses the result and calculates the total number of bytes, something like

    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)