Write Your First Client Application


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

Get a Key

Or create one in the Credentials page.

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:

The PageSpeed Score (0-100) indicates how well optimized a page is. A high score indicates little room for improvement, while a low score indicates more room for improvement. PageSpeed generates a score for each rule group. Currently supported rule groups include 'SPEED' and 'USABILITY'. 'USABILITY' analysis is only performed when the mobile analysis strategy is requested.
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.


  • 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.

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 name Value Description
Required query parameters
url string The URL to fetch and analyze
Optional query parameters
filter_third_party_resources boolean Indicates if third party resources should be filtered out before PageSpeed analysis. (Default: false)
locale string The locale used to localize formatted results
rule string A PageSpeed rule to run; if none are given, all rules are run
screenshot boolean Indicates if binary data containing a screenshot should be included (Default: false)
strategy string The analysis strategy to use

Acceptable values are:
  • "desktop": Fetch and analyze the URL for desktop browsers
  • "mobile": Fetch and analyze the URL for mobile devices

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 mobile PageSpeed results for the URL https://developers.google.com/speed/pagespeed/insights/. 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.


$ curl 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=https://developers.google.com/speed/pagespeed/insights/&strategy=mobile&key=yourAPIKey'


 "kind": "pagespeedonline#result",
 "id": "https://developers.google.com/speed/pagespeed/insights/",
 "responseCode": 200,
 "title": "PageSpeed Insights",
 "ruleGroups": {
  "SPEED": {
   "score": 94
   "score": 100
 "pageStats": {
  "numberResources": 17,
  "numberHosts": 8,
  "totalRequestBytes": "2570",
  "numberStaticResources": 13,
  "htmlResponseBytes": "70113",
  "imageResponseBytes": "14985",
  "javascriptResponseBytes": "709324",
  "numberJsResources": 10
 "formattedResults": {
  "locale": "en_US",
  "ruleResults": {
   "AvoidLandingPageRedirects": {
    "localizedRuleName": "Avoid landing page redirects",
    "ruleImpact": 0.0,
    "groups": [
    "summary": {
     "format": "Your page has no redirects. Learn more about {{BEGIN_LINK}}avoiding landing page redirects{{END_LINK}}.",
     "args": [
       "type": "HYPERLINK",
       "key": "LINK",
       "value": "https://developers.google.com/speed/docs/insights/AvoidRedirects"
   "AvoidPlugins": {
    "localizedRuleName": "Avoid plugins",
    "ruleImpact": 0.0,
    "groups": [
    "summary": {
     "format": "Your page does not appear to use plugins, which would prevent content from being usable on many platforms. Learn more about the importance of {{BEGIN_LINK}}avoiding plugins{{END_LINK}}.",
     "args": [
       "type": "HYPERLINK",
       "key": "LINK",
       "value": "https://developers.google.com/speed/docs/insights/AvoidPlugins"
   "UseLegibleFontSizes": {
    "localizedRuleName": "Use legible font sizes",
    "ruleImpact": 0.0,
    "groups": [
    "summary": {
     "format": "The text on your page is legible. Learn more about {{BEGIN_LINK}}using legible font sizes{{END_LINK}}.",
     "args": [
       "type": "HYPERLINK",
       "key": "LINK",
       "value": "https://developers.google.com/speed/docs/insights/UseLegibleFontSizes"
 "version": {
  "major": 1,
  "minor": 15

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 https://developers.google.com/speed/pagespeed/insights/. 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):

// 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 = 'https://developers.google.com/speed/pagespeed/insights/';

Next, fetch PageSpeed Results from the PageSpeed Insights API:

var API_URL = 'https://www.googleapis.com/pagespeedonline/v2/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,
    'key=' + API_KEY,
  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.

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

// 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);

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

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,
    'chd=t:' + score,
    'chxl=0:|' + score,
  var i = document.createElement('img');
  i.src = CHART_API_URL + query;
  document.body.insertBefore(i, null);

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.

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});
  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; }

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:

  {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;
  // Construct the query to send to the Google Chart Tools.
  var query = [
    'chts=' + ['000000', 16].join(','),
    'chco=' + colors.join('|'),
    'chd=t:' + data.join(','),
    'chdl=' + labels.join('|'),
    'chds=0,' + largestSingleCategory,
  var i = document.createElement('img');
  i.src = 'http://chart.apis.google.com/chart?' + query;
  document.body.insertBefore(i, null);

Demo Video

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