PageSpeed Insights API 시작하기

PageSpeed Insights API를 사용하면 다음과 같은 작업을 할 수 있습니다.

  • 웹페이지의 성능을 측정합니다.
  • 페이지의 실적, 접근성, 검색엔진 최적화를 개선하는 방법에 관한 제안을 받습니다.
  • 페이지를 프로그레시브 웹 앱으로 전환하는 방법을 알아보세요.

PageSpeed Insights API는 Chrome 사용자 환경 보고서에서 실제 데이터를 반환하고 Lighthouse에서 실험실 데이터를 반환합니다.

기본 요건

이 가이드에서는 사용자가 명령줄 인터페이스 및 웹 개발에 대한 일반적인 지식을 가지고 있다고 가정합니다.

선택사항: API 키 설정

PageSpeed Insights API만 사용해 보는 경우에는 API 키가 필요하지 않습니다. API를 자동화된 방식으로 사용하고 초당 여러 쿼리를 실행하려면 API 키가 필요합니다.

API 키 획득 및 사용

키 가져오기

또는 사용자 인증 정보 페이지에서 만드세요.

API 키가 있으면 애플리케이션은 모든 요청 URL에 쿼리 매개변수 key=yourAPIKey를 추가할 수 있습니다.

API 키는 URL에 포함하기에 안전합니다. 인코딩이 전혀 필요하지 않습니다.

API 탐색기

코드를 작성하지 않고 PageSpeed Insights API를 호출하려면 API 탐색기를 확인하세요.

CURL

명령줄에서 PageSpeed Insights API를 사용해 보려면 다음 단계를 따르세요.

  1. 터미널을 엽니다.
  2. 다음 명령어를 실행합니다. API 키를 사용할 경우 &key=yourAPIKey를 추가합니다.

    curl https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://developers.google.com
    

    응답은 JSON 객체입니다. 응답 객체의 각 속성에 대해 자세히 알아보려면 응답을 참조하세요.

    {
     "captchaResult": "CAPTCHA_NOT_NEEDED",
     "kind": "pagespeedonline#result",
     "id": "https://developers.google.com/",
     "loadingExperience": {
      "id": "https://developers.google.com/",
      "metrics": {
       "FIRST_CONTENTFUL_PAINT_MS": {
        "percentile": 3482,
        "distributions": [
         {
          "min": 0,
          "max": 1000,
          "proportion": 0.37151728768042963
         },
         {
          "min": 1000,
          "max": 2500,
          "proportion": 0.4244153519077991
         },
         {
          "min": 2500,
          "proportion": 0.2040673604117713
         }
        ],
        "category": "SLOW"
       },
       "FIRST_INPUT_DELAY_MS": {
        "percentile": 36,
        "distributions": [
         {
          "min": 0,
          "max": 50,
          "proportion": 0.960628961482204
         },
         {
          "min": 50,
          "max": 250,
          "proportion": 0.02888834714773281
         },
         {
          "min": 250,
          "proportion": 0.010482691370063388
         }
        ],
        "category": "FAST"
       }
      },
      "overall_category": "SLOW",
      "initial_url": "https://developers.google.com/"
     },
     "originLoadingExperience": {
      "id": "https://developers.google.com",
      "metrics": {
       "FIRST_CONTENTFUL_PAINT_MS": {
        "percentile": 2761,
        "distributions": [
         {
          "min": 0,
          "max": 1000,
          "proportion": 0.4236433226493666
         },
         {
          "min": 1000,
          "max": 2500,
          "proportion": 0.45045120795679117
         },
         {
          "min": 2500,
          "proportion": 0.1259054693938423
         }
        ],
        "category": "SLOW"
       },
       "FIRST_INPUT_DELAY_MS": {
        "percentile": 45,
        "distributions": [
         {
          "min": 0,
          "max": 50,
          "proportion": 0.9537371485251699
         },
         {
          "min": 50,
          "max": 250,
          "proportion": 0.03044972719889055
         },
         {
          "min": 250,
          "proportion": 0.01581312427593959
         }
        ],
        "category": "FAST"
       }
      },
      "overall_category": "SLOW",
      "initial_url": "https://developers.google.com/"
     },
     "lighthouseResult": {
      "requestedUrl": "https://developers.google.com/",
      "finalUrl": "https://developers.google.com/",
      "lighthouseVersion": "3.2.0",
      "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/72.0.3584.0 Safari/537.36",
      "fetchTime": "2018-11-01T03:03:58.394Z",
      "environment": {
       "networkUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3559.0 Safari/537.36",
       "hostUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/72.0.3584.0 Safari/537.36",
       "benchmarkIndex": 590.0
      },
      "runWarnings": [],
      "configSettings": {
       "emulatedFormFactor": "desktop",
       "locale": "en-US",
       "onlyCategories": [
        "performance"
       ]
      },
      "audits": {
       "estimated-input-latency": {
        "id": "estimated-input-latency",
        "title": "Estimated Input Latency",
        "description": "The score above is an estimate of how long your app takes to respond to user input, in milliseconds, during the busiest 5s window of page load. If your latency is higher than 50 ms, users may perceive your app as laggy. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/estimated-input-latency).",
        "score": 1.0,
        "scoreDisplayMode": "numeric",
        "displayValue": "30 ms"
       },
       "uses-rel-preconnect": {
        "id": "uses-rel-preconnect",
        "title": "Preconnect to required origins",
        "description": "Consider adding preconnect or dns-prefetch resource hints to establish early connections to important third-party origins. [Learn more](https://developers.google.com/web/fundamentals/performance/resource-prioritization#preconnect).",
        "score": 1.0,
        "scoreDisplayMode": "numeric",
        "details": {
         "headings": [],
         "type": "opportunity",
         "items": [],
         "overallSavingsMs": 0.0
        }
       },
       ...
      },
      "categories": {
       "performance": {
        "id": "performance",
        "title": "Performance",
        "score": 0.96,
        "auditRefs": [
         {
          "id": "first-contentful-paint",
          "weight": 3.0,
          "group": "metrics"
         },
         {
          "id": "first-meaningful-paint",
          "weight": 1.0,
          "group": "metrics"
         },
         ...
        ]
       }
      },
      "categoryGroups": {
       "a11y-element-names": {
        "title": "Elements Have Discernible Names",
        "description": "These are opportunities to improve the semantics of the controls in your application. This may enhance the experience for users of assistive technology, like a screen reader."
       },
       "a11y-language": {
        "title": "Page Specifies Valid Language",
        "description": "These are opportunities to improve the interpretation of your content by users in different locales."
       },
       ...
      },
      "i18n": {
       "rendererFormattedStrings": {
        "varianceDisclaimer": "Values are estimated and may vary.",
        "opportunityResourceColumnLabel": "Opportunity",
        "opportunitySavingsColumnLabel": "Estimated Savings",
        "errorMissingAuditInfo": "Report error: no audit information",
        "errorLabel": "Error!",
        "warningHeader": "Warnings: ",
        "auditGroupExpandTooltip": "Show audits",
        "passedAuditsGroupTitle": "Passed audits",
        "notApplicableAuditsGroupTitle": "Not applicable",
        "manualAuditsGroupTitle": "Additional items to manually check",
        "toplevelWarningsMessage": "There were issues affecting this run of Lighthouse:",
        "scorescaleLabel": "Score scale:",
        "crcLongestDurationLabel": "Maximum critical path latency:",
        "crcInitialNavigation": "Initial Navigation",
        "lsPerformanceCategoryDescription": "[Lighthouse](https://developers.google.com/web/tools/lighthouse/) analysis of the current page on an emulated mobile network. Values are estimated and may vary.",
        "labDataTitle": "Lab Data"
       }
      }
     },
     "analysisUTCTimestamp": "2018-11-01T03:03:58.394Z"
    }
    

JavaScript

JavaScript에서 PageSpeed Insights API를 사용해 보려면 다음 단계를 따르세요.

  1. 아래 코드를 복사합니다. 이 코드는 PageSpeed Insights API를 사용하여 https://developers.google.com의 성능을 측정한 후 결과를 표시합니다.

    <script>
    function run() {
      const url = setUpQuery();
      fetch(url)
        .then(response => response.json())
        .then(json => {
          // See https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed#response
          // to learn more about each of the properties in the response object.
          showInitialContent(json.id);
          const cruxMetrics = {
            "First Contentful Paint": json.loadingExperience.metrics.FIRST_CONTENTFUL_PAINT_MS.category,
            "First Input Delay": json.loadingExperience.metrics.FIRST_INPUT_DELAY_MS.category
          };
          showCruxContent(cruxMetrics);
          const lighthouse = json.lighthouseResult;
          const lighthouseMetrics = {
            'First Contentful Paint': lighthouse.audits['first-contentful-paint'].displayValue,
            'Speed Index': lighthouse.audits['speed-index'].displayValue,
            'Time To Interactive': lighthouse.audits['interactive'].displayValue,
            'First Meaningful Paint': lighthouse.audits['first-meaningful-paint'].displayValue,
            'First CPU Idle': lighthouse.audits['first-cpu-idle'].displayValue,
            'Estimated Input Latency': lighthouse.audits['estimated-input-latency'].displayValue
          };
          showLighthouseContent(lighthouseMetrics);
        });
    }
    
    function setUpQuery() {
      const api = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed';
      const parameters = {
        url: encodeURIComponent('https://developers.google.com')
      };
      let query = `${api}?`;
      for (key in parameters) {
        query += `${key}=${parameters[key]}`;
      }
      return query;
    }
    
    function showInitialContent(id) {
      document.body.innerHTML = '';
      const title = document.createElement('h1');
      title.textContent = 'PageSpeed Insights API Demo';
      document.body.appendChild(title);
      const page = document.createElement('p');
      page.textContent = `Page tested: ${id}`;
      document.body.appendChild(page);
    }
    
    function showCruxContent(cruxMetrics) {
      const cruxHeader = document.createElement('h2');
      cruxHeader.textContent = "Chrome User Experience Report Results";
      document.body.appendChild(cruxHeader);
      for (key in cruxMetrics) {
        const p = document.createElement('p');
        p.textContent = `${key}: ${cruxMetrics[key]}`;
        document.body.appendChild(p);
      }
    }
    
    function showLighthouseContent(lighthouseMetrics) {
      const lighthouseHeader = document.createElement('h2');
      lighthouseHeader.textContent = "Lighthouse Results";
      document.body.appendChild(lighthouseHeader);
      for (key in lighthouseMetrics) {
        const p = document.createElement('p');
        p.textContent = `${key}: ${lighthouseMetrics[key]}`;
        document.body.appendChild(p);
      }
    }
    
    run();
    </script>
    
  2. 코드를 HTML 파일에 붙여넣습니다.
  3. 브라우저에서 HTML 파일을 엽니다. 성공적으로 완료되면 페이지가 그림 1과 같이 표시됩니다.

    그림 1. 자바스크립트 데모

다음 단계

  • 응답 객체의 각 속성에 대해 자세히 알아보려면 응답을 참조하세요.
  • 초당 3개 이상의 쿼리를 생성할 계획이라면 API 키를 설정하세요.
  • 성능 측정값이 계산되는 방식을 자세히 알아보려면 PageSpeed Insights API 정보를 참조하세요.

의견

이 페이지가 도움이 되셨나요?