PageSpeed Insights

Developer's Guide (v1): Getting Started

This document explains how to get started using the PageSpeed Insights API.

Contents

  1. Introduction
  2. Before you start
    1. Get familiar with PageSpeed
    2. Get a Google Account
    3. Learn how to identify your application to Google
  3. PageSpeed Insights API background
  4. Invoking the API
    1. Standard query parameters
    2. PageSpeed Insights-specific query parameters
  5. Example API calls
    1. From the command line
    2. From JavaScript
  6. Demo Video

Introduction

This document is intended for developers who want to write applications that can interact with the PageSpeed Insights API.

PageSpeed Insights is a tool that helps developers optimize their web pages by analyzing the pages and generating tailored suggestions to make the pages faster. You can use the PageSpeed Insights API to programmatically generate PageSpeed scores and suggestions.

Before you start

Get a Google Account

You need to have a Google Account so you can get an API key to identify your application to Google. (See below.)

Get familiar with PageSpeed

If you're unfamiliar with PageSpeed, see the PageSpeed Web Performance Best Practices.

Learn how to identify your application to Google

Your application needs to identify itself every time it sends a request to the PageSpeed Insights API, by including an API key with each request.

Acquiring and using an API key

To acquire an API key:

  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the PageSpeed Insights API.
  4. In the sidebar on the left, select Credentials.
  5. The API supports two types of credentials. Create whichever credentials are appropriate for your project:
    • OAuth 2.0: Your application must send an OAuth 2.0 token with any request that accesses private user data. Your application sends a client ID and, possibly, a client secret to obtain a token. You can generate OAuth 2.0 credentials for web applications, service accounts, or installed applications.

    • Public API keys: A request that does not provide an OAuth 2.0 token must send an API key. The key identifies your project and provides API access, quota, and reports. If the key type you need does not already exist, create an API key by selecting Create New Key and then selecting the appropriate key type. Then enter the additional data required for that key type.

After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs.

The API key is safe for embedding in URLs; it doesn't need any encoding.

PageSpeed Insights API background

The results returned by the PageSpeed Insights API include the following types of information:

Score
The PageSpeed Score (0-100) indicates how much faster a page could be. A high score indicates little room for improvement, while a low score indicates more room for improvement.
Rule
PageSpeed analyzes web pages using rules. Each PageSpeed rule is based on general principles of web page performance, such as resource caching, data upload and download size, and client-server round-trip times. PageSpeed rules generate rule results and rule impacts, described below.
Rule Result
A rule result is a suggestion generated by a rule that, if implemented, would make the page faster and increase the PageSpeed score for that page. For instance, if a compressible resource is served uncompressed, the PageSpeed Enable Compression rule would generate a result that recommends that the developer enable compression for that resource.
Rule Impact
Each PageSpeed rule generates an impact number (an unbounded floating point value) that indicates the importance or priority of implementing the rule-result suggestions for the rule, relative to other rules. For instance, if enabling compression would save 1MB, while optimizing images would save 500kB, the Enable Compression rule would have an impact value that is twice that of the Optimize Images rule. An impact of zero indicates that there are no suggestions for improvement for that rule.

Invoking the API

To invoke the API, call the runPagespeed method, specifying the URL, API key, and other parameters in the query string. The following tables summarize the available parameters.

Standard query parameters

All parameters are optional except where noted.

Parameter Meaning Notes
callback Callback function.
  • Name of the JavaScript callback function that handles the response.
  • Used in JavaScript JSON-P requests.
key

API key. (REQUIRED)

  • Your API key identifies your project and provides you with API access, quota, and reports.
  • Obtain your project's API key from the APIs console.
prettyprint

Returns response with identations and line breaks.

  • Returns the response in a human-readable format if true.
  • Default value: true.
  • When this is false, it can reduce the response payload size, which might lead to better performance in some environments.
userIp IP address of the site where the request originates.

PageSpeed Insights-specific query parameters

Parameter Meaning Default
url The URL of the page for which the PageSpeed Insights API should generate results. N/A (REQUIRED)
locale The locale that results should be generated in. See the list of supported locales. If the specified locale is not supported, the default locale is used. en_US
strategy The strategy to use when analyzing the page. Valid values are desktop and mobile. desktop
rule The PageSpeed rules to run. Can be specified multiple times (for example, &rule=AvoidBadRequests&rule=MinifyJavaScript) to request multiple rules. If unspecified, all rules for the current strategy are used. Most users of the API should not need to specify this parameter. all rules for the current strategy

Example API calls

From the command line

You can invoke the PageSpeed Insights API from the Linux/UNIX command line, using a program such as curl.

The following example uses this approach to fetch PageSpeed results for the URL http://code.google.com/speed/page-speed/. The PageSpeed score, page statistics, and PageSpeed formatted results are returned in the JSON data format.

Formatted results are keyed by rule identifiers (such as AvoidBadRequests or MinifyJavaScript), and contain the score and impact for that rule, as well as suggestions generated by the rule that, if implemented, will make the page load faster. To learn more about the fields in the JSON response, see the PageSpeed Insights API Reference document.

Request:

$ curl "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=http://code.google.com/speed/page-speed/&key=yourAPIKey"

Response:

{
 "kind": "pagespeedonline#result",
 "id": "/speed/pagespeed",
 "responseCode": 200,
 "title": "PageSpeed Home",
 "score": 90,
 "pageStats": {
  "numberResources": 22,
  "numberHosts": 7,
  "totalRequestBytes": "2761",
  "numberStaticResources": 16,
  "htmlResponseBytes": "91981",
  "cssResponseBytes": "37728",
  "imageResponseBytes": "13909",
  "javascriptResponseBytes": "247214",
  "otherResponseBytes": "8804",
  "numberJsResources": 6,
  "numberCssResources": 2
 },
 "formattedResults": {
  "locale": "en_US",
  "ruleResults": {
   "AvoidBadRequests": {
    "localizedRuleName": "Avoid bad requests",
    "ruleImpact": 0.0
   },
   ...
   "MinifyJavaScript": {
    "localizedRuleName": "Minify JavaScript",
    "ruleImpact": 0.1417,
    "urlBlocks": [
     {
      "header": {
       "format": "Minifying the following JavaScript resources could reduce their size by $1 ($2% reduction).",
       "args": [
        {
         "type": "BYTES",
         "value": "1.3KiB"
        },
        {
         "type": "INT_LITERAL",
         "value": "0"
        }
       ]
      },
      "urls": [
       {
        "result": {
         "format": "Minifying $1 could save $2 ($3% reduction).",
         "args": [
          {
           "type": "URL",
           "value": "http://code.google.com/js/codesite_tail.pack.04102009.js"
          },
          {
           "type": "BYTES",
           "value": "717B"
          },
          {
           "type": "INT_LITERAL",
           "value": "1"
          }
         ]
        }
       },
       ...
       {
        "result": {
         "format": "Minifying $1 could save $2 ($3% reduction).",
         "args": [
          {
           "type": "URL",
           "value": "http://www.gmodules.com/ig/proxy?url\u003dhttp%3A%2F%2Fjqueryjs.googlecode.com%2Ffiles%2Fjquery-1.2.6.min.js"
          },
          {
           "type": "BYTES",
           "value": "258B"
          },
          {
           "type": "INT_LITERAL",
           "value": "0"
          }
         ]
        }
       }
      ]
     }
    ]
   },
   ...
   "SpriteImages": {
    "localizedRuleName": "Combine images into CSS sprites",
    "ruleImpact": 0.0
   }
  }
 },
 "version": {
  "major": 1,
  "minor": 11
 }
}

From JavaScript

You can invoke the PageSpeed Insights API from JavaScript in the browser, using the callback query parameter and a callback function to generate JSON-P results. This allows you to write rich applications that display PageSpeed data without writing any server-side code.

The following example uses this approach to display PageSpeed results and other information for the URL http://code.google.com/speed/page-speed/. This example also makes use of the Google Chart Tools to visualize the information generated by the PageSpeed Insights API.

First, specify your Google API key (learn more about API keys):

<script>
// Specify your actual API key here:
var API_KEY = 'yourAPIKey';

// Specify the URL you want PageSpeed results for here:
var URL_TO_GET_RESULTS_FOR = 'http://code.google.com/speed/page-speed/';
</script>

Next, fetch PageSpeed Results from the PageSpeed Insights API:

<script>
var API_URL = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?';
var CHART_API_URL = 'http://chart.apis.google.com/chart?';

// Object that will hold the callbacks that process results from the
// PageSpeed Insights API.
var callbacks = {}

// Invokes the PageSpeed Insights API. The response will contain
// JavaScript that invokes our callback with the PageSpeed results.
function runPagespeed() {
  var s = document.createElement('script');
  s.type = 'text/javascript';
  s.async = true;
  var query = [
    'url=' + URL_TO_GET_RESULTS_FOR,
    'callback=runPagespeedCallbacks',
    'key=' + API_KEY,
  ].join('&');
  s.src = API_URL + query;
  document.head.insertBefore(s, null);
}

// Our JSONP callback. Checks for errors, then invokes our callback handlers.
function runPagespeedCallbacks(result) {
  if (result.error) {
    var errors = result.error.errors;
    for (var i = 0, len = errors.length; i < len; ++i) {
      if (errors[i].reason == 'badRequest' && API_KEY == 'yourAPIKey') {
        alert('Please specify your Google API key in the API_KEY variable.');
      } else {
        // NOTE: your real production app should use a better
        // mechanism than alert() to communicate the error to the user.
        alert(errors[i].message);
      }
    }
    return;
  }

  // Dispatch to each function on the callbacks object.
  for (var fn in callbacks) {
    var f = callbacks[fn];
    if (typeof f == 'function') {
      callbacks[fn](result);
    }
  }
}

// Invoke the callback that fetches results. Async here so we're sure
// to discover any callbacks registered below, but this can be
// synchronous in your code.
setTimeout(runPagespeed, 0);
</script>

Using the code above to fetch results from the PageSpeed Insights API, we're now ready to display interesting information in the user's browser using the examples below.

Example 1: Display the PageSpeed score as a Google-O-Meter

This example displays a Google-O-Meter that shows the PageSpeed score for the page being analyzed. For example:

PageSpeed Score: 89

<script>
callbacks.displayPageSpeedScore = function(result) {
  var score = result.score;
  // Construct the query to send to the Google Chart Tools.
  var query = [
    'chtt=Page+Speed+score:+' + score,
    'chs=180x100',
    'cht=gom',
    'chd=t:' + score,
    'chxt=x,y',
    'chxl=0:|' + score,
  ].join('&');
  var i = document.createElement('img');
  i.src = CHART_API_URL + query;
  document.body.insertBefore(i, null);
};
</script>

Example 2: Display top PageSpeed suggestions

This example displays the names of the top PageSpeed suggestions for the page being analyzed, as an unordered list. For example:

  • Leverage browser caching
  • Defer parsing of JavaScript
  • Minify HTML
  • Minify JavaScript

Note: The data needed to display full PageSpeed results is provided by the PageSpeed Insights API, but in order to keep the example simple, not all of that data is used here.

<script>
callbacks.displayTopPageSpeedSuggestions = function(result) {
  var results = [];
  var ruleResults = result.formattedResults.ruleResults;
  for (var i in ruleResults) {
    var ruleResult = ruleResults[i];
    // Don't display lower-impact suggestions.
    if (ruleResult.ruleImpact < 3.0) continue;
    results.push({name: ruleResult.localizedRuleName,
                  impact: ruleResult.ruleImpact});
  }
  results.sort(sortByImpact);
  var ul = document.createElement('ul');
  for (var i = 0, len = results.length; i < len; ++i) {
    var r = document.createElement('li');
    r.innerHTML = results[i].name;
    ul.insertBefore(r, null);
  }
  if (ul.hasChildNodes()) {
    document.body.insertBefore(ul, null);
  } else {
    var div = document.createElement('div');
    div.innerHTML = 'No high impact suggestions. Good job!';
    document.body.insertBefore(div, null);
  }
};

// Helper function that sorts results in order of impact.
function sortByImpact(a, b) { return b.impact - a.impact; }
</script>

Example 3: Display a resource size breakdown pie chart

This example displays a pie chart that shows the resource size breakdown of the page being analyzed. For example:

<script>
var RESOURCE_TYPE_INFO = [
  {label: 'JavaScript', field: 'javascriptResponseBytes', color: 'e2192c'},
  {label: 'Images', field: 'imageResponseBytes', color: 'f3ed4a'},
  {label: 'CSS', field: 'cssResponseBytes', color: 'ff7008'},
  {label: 'HTML', field: 'htmlResponseBytes', color: '43c121'},
  {label: 'Flash', field: 'flashResponseBytes', color: 'f8ce44'},
  {label: 'Text', field: 'textResponseBytes', color: 'ad6bc5'},
  {label: 'Other', field: 'otherResponseBytes', color: '1051e8'},
];

callbacks.displayResourceSizeBreakdown = function(result) {
  var stats = result.pageStats;
  var labels = [];
  var data = [];
  var colors = [];
  var totalBytes = 0;
  var largestSingleCategory = 0;
  for (var i = 0, len = RESOURCE_TYPE_INFO.length; i < len; ++i) {
    var label = RESOURCE_TYPE_INFO[i].label;
    var field = RESOURCE_TYPE_INFO[i].field;
    var color = RESOURCE_TYPE_INFO[i].color;
    if (field in stats) {
      var val = Number(stats[field]);
      totalBytes += val;
      if (val > largestSingleCategory) largestSingleCategory = val;
      labels.push(label);
      data.push(val);
      colors.push(color);
    }
  }
  // Construct the query to send to the Google Chart Tools.
  var query = [
    'chs=300x140',
    'cht=p3',
    'chts=' + ['000000', 16].join(','),
    'chco=' + colors.join('|'),
    'chd=t:' + data.join(','),
    'chdl=' + labels.join('|'),
    'chdls=000000,14',
    'chp=1.6',
    'chds=0,' + largestSingleCategory,
  ].join('&');
  var i = document.createElement('img');
  i.src = 'http://chart.apis.google.com/chart?' + query;
  document.body.insertBefore(i, null);
};
</script>

Demo Video

PageSpeed Insights API demo at Google I/O BootCamp 2011.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.