How to retrieve 'Properly size images' opportunity information from JSON returned by Google PageSpeed Insights API?

65 views Asked by At

I have a JavaScript script that uses PageSpeed Insights API. It is easy to get some basic metrics from the JSON object. Here is how I get the performance score:

const performance = data.lighthouseResult.categories.performance.score * 100;

Now I would like to retrieve the 'Properly size images' opportunity information. For example, I would like to get the 15.30s and potential savings (3,055.8KiB) from this audit: enter image description here

I tried

data.lighthouseResult.audits['image-size-responsive'].score

but that returns 'undefined'.

How can I navigate to those figures in the JSON object and is there any documentation that covers that type information?

1

There are 1 answers

0
Brendan Kenny On BEST ANSWER

There are some docs, though they won't typically be detailed enough for your purposes. The PageSpeed Insights API itself documents the API response, but leaves the audits field largely blank.

The more detailed layout of the individual audit results can be found in the Lighthouse source, first under audit-result.d.ts and then (what you're probably most interested in, audit-details.d.ts.

However, those just lay out the union of what the individual audit results can look like. They're helpful in that they can guide you to what can and won't be included in the results, but they don't contain any audit-specific information about what will be found.

In the end, you mostly have to inspect some of the JSON responses you get. The audit in your screenshot has id uses-responsive-images (which can be learned from the html id of the audit in the report page, is found in the path of the docs links in the audit descriptions, or you can search the JSON response for the strings you see in the HTML report).

What you'll need is under data.lighthouseResult.audits['uses-responsive-images']. An abbreviated view of that object:

{
  "id": "uses-responsive-images",
  "numericValue": 15300,
  "numericUnit": "millisecond",
  "details": {
    "type": "opportunity",
    "items": [{
      "url": "https://example.com/large.png",
      "totalBytes": 3130700,
      "wastedBytes": 3129140
    }]
  }
}

there's a bunch of other information in there, so it may be worth looking into the object further to see what might be useful to you.