Magicode logo
Magicode
10 min read

GAS で集計(Google PageSpeed 編)

https://cdn.magicode.io/media/notebox/7605ed39-88c1-4353-a77b-bc997a7603a6.jpeg

Google PageSpeed について

Google が提供する、ページが利用者にとって、どれくらい使いやすいかを示した指標です。SEOにも関係するので、以下の項目については押さえておきましょう。すべての項目において、少ないほど良い評価になります。
  • First ContentFul Paint -- 要求を出してからコンテンツが最初に表示されるまでの時間です。
  • Speed Index -- 表示するまでの時間とその割合を数値化したものです。
  • Largest Contentful Paint -- 画面内にある最大のコンテンツが表示されるまでの時間です。画面が無反応になっている時間が長いとストレスですよね。
  • Time to Interactive -- 画面操作できるようになるまでの時間です。時間がかかってしまうと、画面上のものがクリックできるかどうかがわからない状態になっています。
  • Total Blocking Time -- JavaScript の初期化などの実行で他の処理をせき止めている時間です。あまり大きな処理をしていると、ブラウザの負荷になってしまいます。
  • Cumulative Layout Shift -- 描画完了までの間に、表示されているものがずれる程度をあらわしています。 いったん画面に表示されているものをクリックしようとしたときに違うものをクリックしてしまうとストレスですよね。

Google PageSpeed の集計

集計を行う場合、ツールで実際に測定することになります。結果画面のレイアウトは以下のとおり。各項目をコピーしてスプレッドシートに貼り付けるのは大変です。

スクリプト環境の準備

  1. PageSpeed API を有効にします。まずGoogle SpreadSheet の Apps Script から「プロジェクトの設定」下のほうにプロジェクト番号がクリックできるところがあるのでクリック、API のライブラリから検索で「pagespeed」で検索すると出てきます。これを有効にします。
  2. スコープの設定を入れます。Apps Script の「プロジェクトの設定」で「「appsscript.json」マニフェスト ファイルをエディタで表示する」をチェックします。するとスクリプトエディタで「appscript.json」が表示されるようになり、スコープの設定ができるようになります。今回 OAuth を使うので、この中に入っている「oauthScopes」のエントリに「openid」を追加します。カーソルの位置です。
  3. スクリプト実装に進みます。

スクリプト実装

他でも紹介しましたが、先頭にテスト関数を置き、スクリプトファイルを開いた際に「Ctrl+R」で気軽にテスト実行されるようにします。 検証するサイトは「https //fujitatakesh.net/」の部分を入れ替えてください。 ちなみに、getRequestはリクエスト状態をロギングするためだけに作成しているので、主処理では不要です。
function test_pageSpeed() {
  console.log(GooglePageSpeed.getData('https://fujitatakesh.net/'));
}

function BATCH_PAGESPEED(_site) {
    const url = Utilities.formatString
      ('https://www.googleapis.com/pagespeedonline/v5/runPagespeed?lighthouseResult.audits&url=%s', encodeURIComponent(_site));
    const prms = {
      muteHttpExceptions: true,
      headers: {
        authorization: 'Bearer ' + ScriptApp.getOAuthToken()
      }
    };
    console.log(['Request', UrlFetchApp.getRequest(url, prms)]);
    const res = UrlFetchApp.fetch(url, prms);
    const sts = res.getResponseCode();
    console.log(['Response', sts, res.getAllHeaders()]);
    const cnt = res.getContentText();
    var ret;
    if (sts !== 200) {
      console.error(cnt);
    } else {
      console.log(cnt);
      try {
        ret = JSON.parse(cnt);
      } catch (_error) {
        console.error(_error);
      }
    }
    return ret;
  }
実行に時間がかかりますが、サイトを評価している最中なので待ちましょう。 応答のうち .loadingExperience.metrics 以下を引っ張ると、一般的なスコアが出る場合があります。
10:20:15	情報	{ CUMULATIVE_LAYOUT_SHIFT_SCORE: 
   { percentile: 1,
     distributions: [ [Object], [Object], [Object] ],
     category: 'FAST' },
  EXPERIMENTAL_INTERACTION_TO_NEXT_PAINT: 
   { percentile: 190,
     distributions: [ [Object], [Object], [Object] ],
     category: 'FAST' },
  EXPERIMENTAL_TIME_TO_FIRST_BYTE: 
   { percentile: 4677,
     distributions: [ [Object], [Object], [Object] ],
     category: 'SLOW' },
  FIRST_CONTENTFUL_PAINT_MS: 
   { percentile: 3376,
     distributions: [ [Object], [Object], [Object] ],
     category: 'SLOW' },
  FIRST_INPUT_DELAY_MS: 
   { percentile: 4,
     distributions: [ [Object], [Object], [Object] ],
     category: 'FAST' },
  LARGEST_CONTENTFUL_PAINT_MS: 
   { percentile: 4188,
     distributions: [ [Object], [Object], [Object] ],
     category: 'SLOW' } }
出ない場合は lighthouseResult 以下を見て詳細を確認しましょう。
10:26:13	情報	Logging output too large. Truncating output. {
  "captchaResult": "CAPTCHA_NOT_NEEDED",
  "kind": "pagespeedonline#result",
  "id": "https://www.fujitatakesh.net/",
  "loadingExperience": {
    "initial_url": "https://www.fujitatakesh.net/"
  },
  "lighthouseResult": {
    "requestedUrl": "https://www.fujitatakesh.net/",
    "finalUrl": "https://www.fujitatakesh.net/",
    "lighthouseVersion": "9.6.6",
    "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/102.0.5005.115 Safari/537.36",
    "fetchTime": "2022-09-02T01:25:57.959Z",
    "environment": {
      "networkUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4695.0 Safari/537.36 Chrome-Lighthouse",
      "hostUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/102.0.5005.115 Safari/537.36",
      "benchmarkIndex": 1029.5
    },
    "runWarnings": [],
    "configSettings": {
      "emulatedFormFactor": "desktop",
      "formFactor": "desktop",
      "locale": "en-US",
      "onlyCategories": [
        "performance"
      ],
      "channel": "lr"
    },
    "audits": {
      "offscreen-images": {
        "id": "offscreen-images",
        "title": "Defer offscreen images",
        "description": "Consider lazy-loading offscreen and hidden images after all critical resources have finished loading to lower time to interactive. [Learn more](https://web.dev/offscreen-images/).",
        "score": 1,
        "scoreDisplayMode": "numeric",
        "details": {
          "type": "opportunity",
          "headings": [],
          "overallSavingsBytes": 0,
          "items": [],
          "overallSavingsMs": 0
        },
        "warnings": [],
        "numericValue": 0,
        "numericUnit": "millisecond"
      },
      "first-meaningful-paint": {
        "id": "first-meaningful-paint",
        "title": "First Meaningful Paint",
        "description": "First Meaningful Paint measures when the primary content of a page is visible. [Learn more](https://web.dev/first-meaningful-paint/).",
        "score": 0.99,
        "scoreDisplayMode": "numeric",
        "displayValue": "0.6 s",
        "numericValue": 620,
        "numericUnit": "millisecond"
      },
      "user-timings": {
        "id": "user-timings",
        "title": "User Timing marks and measures",
        "description": "Consider instrumenting your app with the User Timing API to measure your app's real-world performance during key user experiences. [Learn more](https://web.dev/user-timings/).",
        "score": null,
        "scoreDisplayMode": "notApplicable",
        "details": {
          "items": [],
          "type": "table",
          "headings": []
        }
      },
      "max-potential-fid": {
        "id": "max-potential-fid",
        "title": "Max Potential First Input Delay",
        "description": "The maximum potential First Input Delay that your users could experience is the duration of the longest task. [Learn more](https://web.dev/lighthouse-max-potential-fid/).",
        "score": 1,
        "scoreDisplayMode": "numeric",
        "displayValue": "50 ms",
        "numericValue": 50,
        "numericUnit": "millisecond"
      },
      "full-page-screenshot": {
        "id": "full-page-screenshot",
        "title": "Full-page screenshot",
        "description": "A full-height screenshot of the final rendered page",
        "score": null,
        "scoreDisplayMode": "informative",
        "details": {
          "nodes": {
            "page-6-DIV": {
              "top": 1382,
              "height": 184,
              "right": 448,
              "bottom": 1566,
              "width": 385,
              "left": 63
            },
[省略]

自動実行

これはサイトの評価に時間がかかるため、定期実行を仕掛けてシートに自動記載することを推奨します。 実行日時を付加して、DataRange でシートの中身を引っ張って insertRow すれば簡単に実装できます。

Discussion

コメントにはログインが必要です。