ITHCWY: Robert Ellison's Blog

Automate Google PageSpeed Insights with Apps Script

Upload

Here's a quick script to automatically monitor your Google PageSpeed Insights desktop and mobile scores for a web page:

var pageSpeedApiKey = '...';
var pageSpeedMonitorUrl = '...';

function monitor() {
  var desktop = callPageSpeed('desktop');
  var mobile = callPageSpeed('mobile');
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName('results');
  sheet.appendRow([
                   Utilities.formatDate(new Date(), 'GMT', 'yyyy-MM-dd'),
                   desktop.score,
                   mobile.score
                  ]);
    
    // more available, i.e. desktop.pageStats.numberResources
}

function callPageSpeed(strategy) {
  var pageSpeedUrl = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=' + pageSpeedMonitorUrl + '&key=' + pageSpeedApiKey + '&strategy=' + strategy;
  var response = UrlFetchApp.fetch(pageSpeedUrl);
  var json = response.getContentText();
  return JSON.parse(json);
}

You need a spreadsheet with a tab called results and an API key for PageSpeed Insights (activate the API in the console and create an API key for it, the browser based / JavaScript option). Paste the code above into the script editor for the spreadsheet and add your API key and URL to monitor. Then just choose triggers from the Resources menu and schedule the monitor function to run once per day.

Note that this currently just logs the overall score. There are a bunch of other values returned (like number and types of resources on the page) that you could choose to monitor as well. It would also be easy to extend this to monitor more URLs, or to send you an email if the score drops below a threshold.

Add Comment

All comments are moderated to weed out spam. Email address is optional and is only used to display your Gravatar.