### Setup Lighthouse Plugin Example Template Source: https://github.com/googlechrome/lighthouse/blob/main/docs/recipes/lighthouse-plugin-example/readme.md Commands to set up the Lighthouse plugin example as a development template. This involves creating a directory, downloading the template, and cleaning up temporary files. ```sh mkdir lighthouse-plugin-example && cd lighthouse-plugin-example curl -L https://github.com/GoogleChrome/lighthouse/archive/main.zip | tar -xzv mv lighthouse-main/docs/recipes/lighthouse-plugin-example/* ./ rm -rf lighthouse-main ``` -------------------------------- ### Example Lighthouse Configuration Settings Source: https://github.com/googlechrome/lighthouse/blob/main/docs/understanding-results.md Shows the structure of the configuration object used by Lighthouse, including settings for output format, throttling, and form factor. ```json { "output": [ "json" ], "maxWaitForLoad": 45000, "throttlingMethod": "devtools", "throttling": { "rttMs": 150, "throughputKbps": 1638.4, "requestLatencyMs": 562.5, "downloadThroughputKbps": 1474.5600000000002, "uploadThroughputKbps": 675, "cpuSlowdownMultiplier": 4 }, "gatherMode": false, "disableStorageReset": false, "formFactor": "mobile", "blockedUrlPatterns": null, "additionalTraceCategories": null, "extraHeaders": null, "onlyAudits": null, "onlyCategories": null, "skipAudits": null } ``` -------------------------------- ### Install and Use @sitespeed.io/throttle CLI Source: https://github.com/googlechrome/lighthouse/blob/main/docs/throttling.md This snippet shows how to install the @sitespeed.io/throttle npm package globally and use its command-line interface to set network throttling parameters or predefined profiles. It also includes how to disable throttling. ```sh # Install with npm npm install @sitespeed.io/throttle -g # Ensure you have Node.js installed and npm is in your $PATH (https://nodejs.org/en/download/) # To use the recommended throttling values: throttle --up 768 --down 1638 --rtt 150 # or even simpler (using a predefined profile) throttle 3gfast # To disable throttling throttle --stop ``` -------------------------------- ### Serve Lighthouse Treemap Viewer Source: https://github.com/googlechrome/lighthouse/blob/main/treemap/README.md Starts a local server for the treemap viewer. Use this command to run the application locally. ```sh yarn serve-treemap ``` -------------------------------- ### Example package.json for Lighthouse Plugin Source: https://github.com/googlechrome/lighthouse/blob/main/docs/plugins.md Defines the plugin's name, type, main entry point, and dependencies. Use peerDependencies for Lighthouse and devDependencies for local development. ```json { "name": "lighthouse-plugin-example", "type": "module", "main": "plugin.js", "peerDependencies": { "lighthouse": "^13.4.0" }, "devDependencies": { "lighthouse": "^13.4.0" } } ``` -------------------------------- ### Example plugin.js Configuration Source: https://github.com/googlechrome/lighthouse/blob/main/docs/plugins.md Configures the plugin by specifying audits to run and defining a new category for the report. Ensure the filename matches the 'main' property in package.json. ```js export default { // Additional audits to run on information Lighthouse gathered. audits: [{path: 'lighthouse-plugin-example/audits/has-cat-images.js'}], // A new category in the report for the plugin output. category: { title: 'Cats', description: 'When integrated into your website effectively, cats deliver delight and bemusement.', auditRefs: [{id: 'has-cat-images-id', weight: 1}], }, }; ``` -------------------------------- ### Install and Run Lighthouse Plugin Locally Source: https://github.com/googlechrome/lighthouse/blob/main/docs/recipes/lighthouse-plugin-example/readme.md Commands to install dependencies and run a Lighthouse plugin locally for development. It uses `yarn` for installation and `npx lighthouse` with specific flags to target the plugin. ```sh yarn NODE_PATH=.. npx lighthouse -- https://example.com --plugins=lighthouse-plugin-example --only-categories=lighthouse-plugin-example --view ``` -------------------------------- ### Build Treemap with Watcher Source: https://github.com/googlechrome/lighthouse/blob/main/treemap/README.md Starts a build watch process for the treemap. This command rebuilds the treemap when files change. Requires `brew install entr`. ```sh find treemap | entr -s 'DEBUG=1 yarn build-treemap' open http://localhost:7333/treemap/?debug ``` -------------------------------- ### Install Lighthouse and Plugin as User (npm) Source: https://github.com/googlechrome/lighthouse/blob/main/docs/recipes/lighthouse-plugin-example/readme.md npm command to install Lighthouse and a specific plugin as development dependencies. This is typically done when setting up a project that will utilize the plugin. ```sh npm install -D lighthouse lighthouse-plugin-example ``` -------------------------------- ### Install and Run Lighthouse via Node CLI Source: https://github.com/googlechrome/lighthouse/blob/main/readme.md Provides instructions for installing the Lighthouse package globally using npm or yarn and executing an audit against a specific URL. Requires Node.js version 22 or later. ```shell npm install -g lighthouse # or use yarn: # yarn global add lighthouse lighthouse https://airhorner.com/ ``` -------------------------------- ### Build and Run Lighthouse Integration Tests Source: https://github.com/googlechrome/lighthouse/blob/main/docs/recipes/integration-test/README.md Commands to build Lighthouse, install dependencies for the integration test recipe, and execute the tests using Yarn. ```sh # Be in this folder: docs/recipes/integration-test # Build Lighthouse yarn --cwd ../../.. yarn --cwd ../../.. build-report yarn --cwd ../../.. build-pack # Install deps for this recipe. yarn yarn --cwd ../auth # Run the recipe. yarn test ``` -------------------------------- ### Example Lighthouse Timing Information Source: https://github.com/googlechrome/lighthouse/blob/main/docs/understanding-results.md Illustrates the timing object, which contains the total time in milliseconds spent during the Lighthouse audit process. ```json { "total": 32189 } ``` -------------------------------- ### Integrate @sitespeed.io/throttle with Lighthouse Source: https://github.com/googlechrome/lighthouse/blob/main/docs/throttling.md This example demonstrates how to use @sitespeed.io/throttle to set system-wide network throttling before running Lighthouse. It configures Lighthouse to ignore its internal throttling settings to ensure the external throttling is effective. Finally, it shows how to disable the system throttling. ```sh npm install @sitespeed.io/throttle -g # Enable system traffic throttling throttle 3gfast # Run Lighthouse with its own network throttling disabled (while leaving CPU throttling) lighthouse --throttling-method=devtools \ --throttling.requestLatencyMs=0 \ --throttling.downloadThroughputKbps=0 \ --throttling.uploadThroughputKbps=0 \ https://example.com # Disable the traffic throttling once you see "Gathering trace" throttle --stop ``` -------------------------------- ### Install Dependencies Source: https://github.com/googlechrome/lighthouse/blob/main/core/scripts/legacy-javascript/README.md Installs the necessary dependencies for the LegacyJavaScript validation tool. This command should be run in the root directory of the tool's folder. ```sh yarn ``` -------------------------------- ### Lighthouse Audit Entry Example Source: https://github.com/googlechrome/lighthouse/blob/main/docs/understanding-results.md Example JSON structure for a Lighthouse audit entry, demonstrating properties like id, title, description, score, and auditRefs. ```json { "seo": { "id": "seo", "title": "SEO", "description": "These checks ensure that your page is following basic search engine optimization advice...", "score": 0.54, "auditRefs": [ { "id": "crawlable-anchors", "weight": 1 } ] } } ``` -------------------------------- ### Generate Insight Audits Source: https://github.com/googlechrome/lighthouse/blob/main/core/audits/insights/README.md Use this command to start adding new insight audits. Ensure you have the necessary project setup. ```bash yarn generate-insight-audits ``` -------------------------------- ### Define Custom Lighthouse Configuration Source: https://github.com/googlechrome/lighthouse/blob/main/docs/readme.md Provides an example of a configuration object that extends the default Lighthouse settings to include specific audits. ```json { "extends": "lighthouse:default", "settings": { "onlyAudits": [ "speed-index", "interactive" ] } } ``` -------------------------------- ### Lighthouse Category Group Example Source: https://github.com/googlechrome/lighthouse/blob/main/docs/understanding-results.md Example JSON structure for a Lighthouse category group, showing the title and description for a group of audits. ```json { "metrics": { "title": "Metrics", "description": "These metrics are super cool." } } ``` -------------------------------- ### Run Lighthouse Plugin using npx (User) Source: https://github.com/googlechrome/lighthouse/blob/main/docs/recipes/lighthouse-plugin-example/readme.md Command to run Lighthouse with a specific plugin using `npx`. This method ensures the locally installed version of Lighthouse is used without global installation. ```sh npx --no-install lighthouse -- https://example.com --plugins=lighthouse-plugin-example --view ``` -------------------------------- ### JavaScript: Fetch API for Network Requests Source: https://github.com/googlechrome/lighthouse/blob/main/cli/test/fixtures/baseline.html Demonstrates a basic usage of the Fetch API in JavaScript to initiate a network request for 'baseline.html'. The example includes a `.then()` callback to log a message to the console upon successful completion of the fetch operation. ```javascript fetch('baseline.html').then(() => console.log('fetched')); ``` -------------------------------- ### Run Lighthouse via CLI with Headless Chrome Source: https://github.com/googlechrome/lighthouse/blob/main/docs/headless-chrome.md Configures the environment and executes a Lighthouse audit using the --headless flag. Requires Node.js 22+ and Chromium installed on the system. ```shell curl -sL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt-get install -y nodejs npm apt-get install chromium npm i -g lighthouse lighthouse --chrome-flags="--headless" https://github.com ``` -------------------------------- ### Launch Browser and Create Page with Puppeteer Source: https://github.com/googlechrome/lighthouse/blob/main/docs/recipes/auth/README.md Initializes a new browser instance using Puppeteer and creates a new tab (page). The 'headless' option is set to 'new' for running in the background, and 'slowMo' adds a delay to observe the automation steps. This is the starting point for browser automation. ```javascript const browser = await puppeteer.launch({ // Set to false if you want to see the script in action. headless: 'new', slowMo: 50, }); const page = await browser.newPage(); ``` -------------------------------- ### Chrome Debugging Protocol Event Binding Example (JavaScript) Source: https://github.com/googlechrome/lighthouse/blob/main/docs/architecture.md Demonstrates the correct way to bind to Chrome Debugging Protocol events and enable domains. Event binding should occur before enabling the domain to ensure no events are missed. This is crucial for capturing network requests and page state changes. ```javascript driver.defaultSession.on('Security.securityStateChanged', state => { /* ... */ }); // event binding is synchronous driver.defaultSession.sendCommand('Security.enable'); ``` -------------------------------- ### Example Trace Event Structure (JSON) Source: https://github.com/googlechrome/lighthouse/blob/main/docs/architecture.md Illustrates the structure of a raw trace event as used in Lighthouse. Each event contains metadata such as process ID, thread ID, timestamp, event type, category, name, and duration. This format is fundamental for performance analysis. ```json { "pid": 41904, // process ID "tid": 1295, // thread ID "ts": 1676836141, // timestamp in microseconds "ph": "X", // trace event type "cat": "toplevel", // trace category from which this event came "name": "MessageLoop::RunTask", // relatively human-readable description of the trace event "dur": 64, // duration of the task in microseconds "args": {}, // contains additional data such as frame when applicable } ``` -------------------------------- ### Capture a Page State Snapshot in Node.js Source: https://github.com/googlechrome/lighthouse/blob/main/docs/user-flows.md This code example shows how to capture a static snapshot of a page's current state using Lighthouse's startFlow and snapshot methods. It utilizes Puppeteer to navigate and interact with the page before calling the snapshot function. The generated report is then saved to an HTML file. ```javascript import {writeFileSync} from 'fs'; import puppeteer from 'puppeteer'; import {startFlow} from 'lighthouse'; const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); const flow = await startFlow(page); await page.click('#expand-sidebar'); await flow.snapshot(); await browser.close(); writeFileSync('report.html', await flow.generateReport()); ``` -------------------------------- ### Example Audit Using Network Records Source: https://github.com/googlechrome/lighthouse/blob/main/docs/plugins.md This audit checks for specific headers in network requests. It requires the `DevtoolsLog` artifact and uses the `NetworkRecords` utility to process the log. The `context` argument is important for caching network request computations. ```js import {Audit, NetworkRecords} from 'lighthouse'; class HeaderPoliceAudit { static get meta() { return { id: 'header-police-audit-id', title: 'All headers stripped of debug data', failureTitle: 'Headers contained debug data', description: 'Pages should mask debug data in production.', requiredArtifacts: ['DevtoolsLog'], }; } static async audit(artifacts, context) { // Request the network records from the devtools log. // The `context` argument is passed in to allow Lighthouse to cache the result and not re-compute the network requests for every audit that needs them. const devtoolsLog = artifacts.DevtoolsLog; const requests = await NetworkRecords.request(devtoolsLog, context); // Do whatever you need to with the network requests. const badRequests = requests.filter(request => request.responseHeaders.some(header => header.name.toLowerCase() === 'x-debug-data') ); return { score: badRequests.length === 0 ? 1 : 0, }; } } export default HeaderPoliceAudit; ``` -------------------------------- ### Lighthouse Result Object (LHR) Example Source: https://github.com/googlechrome/lighthouse/blob/main/docs/understanding-results.md This JSON structure represents a typical Lighthouse Result Object, detailing metadata like version, fetch time, user agent, requested URL, and placeholders for audit results, configuration, timing, and categories. ```json { "lighthouseVersion": "5.1.0", "fetchTime": "2019-05-05T20:50:54.185Z", "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3358.0 Safari/537.36", "requestedUrl": "http://example.com", "mainDocumentUrl": "https://www.example.com/", "finalDisplayedUrl": "https://www.example.com/", "audits": {...}, "configSettings": {...}, "timing": {...}, "categories": {...}, } ``` -------------------------------- ### JavaScript: Triggering Dialog and Popover Elements Source: https://github.com/googlechrome/lighthouse/blob/main/cli/test/fixtures/baseline.html Provides JavaScript code examples for triggering modal dialogs and popovers using their respective `showModal()` and `showPopover()` methods. These snippets illustrate how to programmatically control the visibility of these common UI components. ```javascript document.getElementById('d').showModal(); ``` ```javascript document.getElementById('p').showPopover(); ``` -------------------------------- ### Initialize Lighthouse Report with JSON Data Source: https://github.com/googlechrome/lighthouse/blob/main/report/assets/standalone-template.html This snippet initializes the Lighthouse report by embedding the JSON data and executing the main rendering script. It requires the `%%LIGHTHOUSE_JSON%%` placeholder to be replaced with actual JSON data and `%%LIGHTHOUSE_JAVASCRIPT%%` with the report rendering JavaScript. The `__initLighthouseReport__()` function is then called to start the rendering process. ```javascript window.__LIGHTHOUSE_JSON__ = %%LIGHTHOUSE_JSON%%; %%LIGHTHOUSE_JAVASCRIPT%% __initLighthouseReport__(); //# sourceURL=compiled-reportrenderer.js console.log('window.__LIGHTHOUSE_JSON__', __LIGHTHOUSE_JSON__); ``` -------------------------------- ### CSS Animation for Font Size Change Source: https://github.com/googlechrome/lighthouse/blob/main/cli/test/fixtures/perf/trace-elements.html This CSS code defines an animation that modifies the font size of an element. It requires a keyframes rule to specify the animation's start and end states. The animation is applied to an element with the ID 'animate-me'. ```css #animate-me { width: 100px; height: 100px; font-size: 20pt; background-color: red; animation-name: anim; animation-duration: 1s; } @keyframes anim { from {font-size: 20pt;} to {font-size: 10pt;} } ``` -------------------------------- ### Audit Description Examples Source: https://github.com/googlechrome/lighthouse/blob/main/docs/plugins.md Examples of audit descriptions that provide context and link to further resources. ```text Interactive elements like buttons and links should be large enough (48x48px), and have enough space around them, to be easy enough to tap without overlapping onto other elements. [Learn more](https://developers.google.com/web/fundamentals/accessibility/accessible-styles#multi-device_responsive_design). All sites should be protected with HTTPS, even ones that don't handle sensitive data. HTTPS prevents intruders from tampering with or passively listening in on the communications between your app and your users, and is a prerequisite for HTTP/2 and many new web platform APIs. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/https) ``` -------------------------------- ### Audit Title Examples Source: https://github.com/googlechrome/lighthouse/blob/main/docs/plugins.md Examples of effective audit titles that describe the present state of the page. ```text Document has a "" element Document does not have a "<title>" element Uses HTTPS Does not use HTTPS Tap targets are sized appropriately Tap targets are not sized appropriately ``` -------------------------------- ### Prepare Release Package Source: https://github.com/googlechrome/lighthouse/blob/main/docs/releasing.md This script packages all necessary components for publishing the release. ```sh bash ./core/scripts/release/prepare-package.sh ``` -------------------------------- ### Checkout and Prepare DevTools Frontend Source: https://github.com/googlechrome/lighthouse/blob/main/docs/releasing.md Commands to checkout a specific Lighthouse version and prepare the DevTools frontend for a Chromium CL. This involves updating the DevTools frontend with the new Lighthouse revision. ```sh git checkout vx.x.x # Checkout the specific version. yarn devtools ~/src/devtools/devtools-frontend cd ~/src/devtools/devtools-frontend git new-branch rls git commit -am "[Lighthouse] Roll Lighthouse x.x.x" git cl upload -b 40543651 ``` -------------------------------- ### Initialize File System - JavaScript Source: https://github.com/googlechrome/lighthouse/blob/main/cli/test/fixtures/dobetterweb/dbw_tester.html Initializes the temporary file system and creates a unique PNG file within its root. It then creates an image element using the file's URL and appends it to the document body. Error handling is included via console.error. ```javascript function onInitFs(fs) { fs.root.getFile(`empty-${Math.random()}.png`, {create: true, exclusive: true}, function (fileEntry) { const img = document.createElement('img'); img.src = fileEntry.toURL(); document.body.append(img); }, console.error); } window.webkitRequestFileSystem(window.TEMPORARY, 1024 * 1024, onInitFs, console.error); ``` -------------------------------- ### Run Lighthouse with Custom Config Source: https://github.com/googlechrome/lighthouse/blob/main/docs/recipes/custom-gatherer-puppeteer/readme.md Execute Lighthouse with a custom configuration file. Ensure the config file is correctly specified using the --config-path flag. ```sh lighthouse --config-path=custom-config.js https://www.example.com ``` -------------------------------- ### Build Lighthouse for DevTools Source: https://github.com/googlechrome/lighthouse/blob/main/build/readme.md Run these commands to build the Lighthouse bundle for Chrome DevTools. Use the DEBUG flag to skip minification. ```sh yarn devtools DEBUG=1 yarn devtools # or use this command to skip minification ``` -------------------------------- ### Run Lighthouse with Custom Config Source: https://github.com/googlechrome/lighthouse/blob/main/docs/recipes/custom-audit/readme.md Execute Lighthouse with a custom audit configuration using the `--config-path` flag. Ensure the specified configuration file exists. ```sh lighthouse --config-path=custom-config.js https://example.com ``` -------------------------------- ### Execute Lighthouse CLI with Debug Port Source: https://github.com/googlechrome/lighthouse/blob/main/docs/running-at-scale.md Demonstrates how to launch a debuggable instance of Chrome and execute a Lighthouse audit against it. This pattern is useful for advanced configurations but requires careful management of the Chrome profile to ensure reproducible results. ```bash chrome-debug --port=9222 lighthouse <url> --port=9222 ``` -------------------------------- ### Run Lighthouse Lantern Trace Collection Source: https://github.com/googlechrome/lighthouse/blob/main/core/scripts/lantern/collect/README.md Executes the Lighthouse Lantern trace collection script locally. Requires a WPT key and sufficient memory. Output is saved to `dist/collect-lantern-traces` and zipped. ```sh DEBUG=1 WPT_KEY=... node --max-old-space-size=4096 collect.js ``` -------------------------------- ### WebMCP Testing Ground - Declarative Tool Source: https://github.com/googlechrome/lighthouse/blob/main/cli/test/fixtures/webmcp/webmcp_tester.html This snippet demonstrates a valid declarative tool setup within the WebMCP testing ground. ```html <form> <input type="text" placeholder="Search"> </form> ``` -------------------------------- ### Prepare Release Commit Source: https://github.com/googlechrome/lighthouse/blob/main/docs/releasing.md Use this script to prepare the commit for a new release. Replace 'x.x.x' with the target version number. ```sh bash ./core/scripts/release/prepare-commit.sh x.x.x ``` -------------------------------- ### Run Lighthouse Lantern Trace Collection on GCP Source: https://github.com/googlechrome/lighthouse/blob/main/core/scripts/lantern/collect/README.md Initiates the Lighthouse Lantern trace collection process on Google Cloud Platform. Requires a WPT key. ```sh WPT_KEY=... core/scripts/lantern/collect/gcp-create-and-run.sh ``` -------------------------------- ### Example Audit Result: HTTPS Check Source: https://github.com/googlechrome/lighthouse/blob/main/docs/understanding-results.md Demonstrates the structure of a single audit result, including its ID, title, description, score, display mode, and detailed information about insecure requests. ```json { "is-on-https": { "id": "is-on-https", "title": "Does not use HTTPS", "description": "All sites should be protected with HTTPS, even ones that don't handle sensitive data. HTTPS prevents intruders from tampering with or passively listening in on the communications between your app and your users, and is a prerequisite for HTTP/2 and many new web platform APIs. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/https).", "score": 0, "scoreDisplayMode": "binary", "displayValue": "1 insecure request found", "details": { "type": "table", "headings": [ { "key": "url", "valueType": "url", "label": "Insecure URL" } ], "items": [ { "url": "http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" } ] } }, "custom-audit": { "name": "custom-audit", ... } } ``` -------------------------------- ### Mocking Modules in ESM with Testdouble Source: https://github.com/googlechrome/lighthouse/blob/main/docs/hacking-tips.md Demonstrates how to mock modules in an ES Module environment using `testdouble` and dynamic imports. This is necessary because `mocha` does not hoist mocks, requiring imports that depend on mocked modules to be loaded after the mock is applied. ```javascript import jestMock from 'jest-mock'; import * as td from 'testdouble'; await td.replaceEsm('./module-to-mock.js', { mockedFunction: jestMock.fn(), }); // module-to-mock.js is imported somewhere in the dependency tree of root-module.js const rootModule = await import('./root-module.js'); ``` -------------------------------- ### Update Lighthouse in DevTools MCP Source: https://github.com/googlechrome/lighthouse/blob/main/docs/releasing.md Steps to update Lighthouse within the chrome-devtools-mcp repository. This involves updating package.json, installing dependencies, checking out the corresponding Lighthouse revision, and bundling the changes. ```sh # From the `chrome-devtools-mcp` repo: # 1. Update version in `package.json` and run `npm install`. # 2. Checkout corresponding LH revision to sibling `../lighthouse`. # 3. Run `npm run update-lighthouse`. # 4. Commit the bundle. Update `tests/third_party_notices.test.ts` if new dependencies are added. ``` -------------------------------- ### Run Lighthouse Programmatically in Node.js Source: https://github.com/googlechrome/lighthouse/blob/main/docs/readme.md Demonstrates the full lifecycle of a programmatic Lighthouse run, including launching a headless Chrome instance, executing the audit, and processing the resulting report and data object. ```javascript import fs from 'fs'; import lighthouse from 'lighthouse'; import * as chromeLauncher from 'chrome-launcher'; const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']}); const options = {logLevel: 'info', output: 'html', onlyCategories: ['performance'], port: chrome.port}; const runnerResult = await lighthouse('https://example.com', options); // `.report` is the HTML report as a string const reportHtml = runnerResult.report; fs.writeFileSync('lhreport.html', reportHtml); // `.lhr` is the Lighthouse Result as a JS object console.log('Report is done for', runnerResult.lhr.finalDisplayedUrl); console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100); chrome.kill(); ``` -------------------------------- ### Example Custom Audit: Cat Image Check Source: https://github.com/googlechrome/lighthouse/blob/main/docs/plugins.md Defines a custom audit class with metadata and audit logic. The 'meta' property includes audit details, and the 'audit' function returns the score and numeric value. ```js import {Audit} from 'lighthouse'; class CatAudit extends Audit { static get meta() { return { id: 'has-cat-images-id', title: 'Page has least one cat image', failureTitle: 'Page does not have at least one cat image', description: 'Pages should have lots of cat images to keep users happy. ' + 'Consider adding a picture of a cat to your page improve engagement.', requiredArtifacts: ['ImageElements'], }; } static audit(artifacts) { // Artifacts requested in `requiredArtifacts` above are passed to your audit. // See the "API -> Plugin Audits" section below for what artifacts are available. const images = artifacts.ImageElements; const catImages = images.filter(image => image.src.toLowerCase().includes('cat')); return { // Give users a 100 if they had a cat image, 0 if they didn't. score: catImages.length > 0 ? 1 : 0, // Also return the total number of cat images that can be used by report JSON consumers. numericValue: catImages.length, }; } } export default CatAudit; ``` -------------------------------- ### Monitor and Terminate GCP Collection Instances Source: https://github.com/googlechrome/lighthouse/blob/main/core/scripts/gcp-collection/README.md Commands to check the status of active Lighthouse collection jobs, download collected data, and terminate cloud instances upon completion. ```bash # Check status and download data bash core/scripts/gcp-collection/fleet-status.sh # Check status and terminate finished instances bash core/scripts/gcp-collection/fleet-status.sh --kill ``` -------------------------------- ### Configure Lighthouse for desktop user flows Source: https://github.com/googlechrome/lighthouse/blob/main/docs/user-flows.md Shows how to initialize a Lighthouse user flow specifically for desktop environments using the built-in desktopConfig. ```javascript import puppeteer from 'puppeteer'; import {startFlow, desktopConfig} from 'lighthouse'; const browser = await puppeteer.launch(); const page = await browser.newPage(); const flow = await startFlow(page, { config: desktopConfig, }); await flow.navigate('https://example.com'); ``` -------------------------------- ### Define UIStrings with JSDoc (JavaScript) Source: https://github.com/googlechrome/lighthouse/blob/main/core/lib/i18n/README.md This JavaScript example demonstrates how to define UIStrings within a module using an object literal. Each string must be accompanied by a JSDoc comment providing a description for translation purposes. ```javascript const UIStrings = { /** Imperative title of a Lighthouse audit that ... */ title: 'Minify CSS', }; ``` -------------------------------- ### Animate DOM Element with Web Animations API Source: https://github.com/googlechrome/lighthouse/blob/main/cli/test/fixtures/perf/animations.html Uses the Web Animations API to programmatically animate the width of an element with the ID 'animated-boi'. This triggers a layout change over a duration of 3000 milliseconds. ```javascript document.getElementById("animated-boi").animate([ {width: '100px'}, {width: '200px'} ], 3000); ``` -------------------------------- ### Sync DevTools e2e Test Resources Source: https://github.com/googlechrome/lighthouse/blob/main/third-party/devtools-tests/README.md Use rsync to synchronize DevTools end-to-end test resources from the local devtools-frontend directory to the lighthouse third-party directory. Excludes OWNERS and DIR_METADATA files. ```sh rsync -ahvz --exclude='OWNERS' --exclude='DIR_METADATA' ~/src/devtools/devtools-frontend/test/e2e/lighthouse/ third-party/devtools-tests/e2e/lighthouse/ ``` ```sh rsync -ahvz --exclude='OWNERS' --exclude='DIR_METADATA' ~/src/devtools/devtools-frontend/test/e2e/resources/lighthouse/ third-party/devtools-tests/e2e/resources/lighthouse/ ``` -------------------------------- ### Post Lighthouse Reports to GitHub Gists Source: https://github.com/googlechrome/lighthouse/blob/main/docs/headless-chrome.md Automates the generation of a Lighthouse JSON report and uploads it to a GitHub Gist using curl and jq. This allows the report to be viewed via the Lighthouse Viewer. ```shell lighthouse "http://localhost" --chrome-flags="--no-sandbox --headless" \ --output json \ | jq -r "{ description: \"YOUR TITLE HERE\", public: \"false\", files: {\"$(date "+%Y%m%d").lighthouse.report.json\": {content: (. | tostring) }}}" \ | curl -sS -X POST -H 'Content-Type: application/json' \ -u ${GITHUB_OWNER}:${GITHUB_TOKEN} \ -d @- https://api.github.com/gists > results.gist ``` -------------------------------- ### Collect and upload Lighthouse reports using Lighthouse CI Source: https://github.com/googlechrome/lighthouse/blob/main/docs/variability.md Uses the Lighthouse CI CLI to perform multiple runs against a URL and save the results to the filesystem. This approach simplifies the process of gathering data for statistical analysis. ```bash npx -p @lhci/cli lhci collect --url https://example.com -n 5 npx -p @lhci/cli lhci upload --target filesystem --outputDir ./path/to/dump/reports ``` ```bash npx -p @lhci/cli lhci collect --url https://example.com -n 5 --mode psi --psiApiKey xXxXxXx npx -p @lhci/cli lhci upload --target filesystem --outputDir ./path/to/dump/reports ``` -------------------------------- ### Define CSS Animations and Keyframes Source: https://github.com/googlechrome/lighthouse/blob/main/cli/test/fixtures/perf/animations.html Defines styles and keyframe animations for two elements, 'animated-boi' and 'composited-boi'. It demonstrates layout-impacting animations like height and font-size changes versus compositing-only changes like opacity. ```css #animated-boi { width: 100px; height: 100px; font-size: 20pt; background-color: red; animation: alpha 4s, beta 2s; } #composited-boi { width: 100px; height: 100px; background-color: green; animation: gamma 4s; } @keyframes alpha { from {height: 100px;} to {height: 200px;} } @keyframes beta { from {font-size: 20pt;} to {font-size: 10pt;} } @keyframes gamma { from {opacity: 1;} to {opacity: 0;} } ``` -------------------------------- ### Run Lighthouse Programmatically in Node.js Source: https://github.com/googlechrome/lighthouse/blob/main/docs/headless-chrome.md Uses the lighthouse and chrome-launcher npm packages to programmatically launch a headless browser and run an audit. Returns a promise containing the audit results. ```javascript const lighthouse = require('lighthouse'); const chromeLauncher = require('chrome-launcher'); function launchChromeAndRunLighthouse(url, flags = {}, config = null) { return chromeLauncher.launch(flags).then(chrome => { flags.port = chrome.port; return lighthouse(url, flags, config).then(results => { chrome.kill(); return results; }); }); } const flags = { chromeFlags: ['--headless'] }; launchChromeAndRunLighthouse('https://github.com', flags).then(results => { // Use results! }); ``` -------------------------------- ### Direct ICU Replacement in JavaScript Source: https://github.com/googlechrome/lighthouse/blob/main/core/lib/i18n/README.md Demonstrates direct ICU replacement for simple string substitutions in JavaScript. It uses JSDoc-like syntax for descriptions and examples, where `{some_name}` is replaced with a variable at runtime. This is suitable for proper nouns, code, or dynamic text. ```javascript const UIStrings = { /** * @description Error message explaining ... * @example {NO_SPEEDLINE_FRAMES} errorCode */ didntCollectScreenshots: `Chrome didn't .... ({errorCode})`, }; ``` -------------------------------- ### Complex ICU Replacement (Number Formatting) in JavaScript Source: https://github.com/googlechrome/lighthouse/blob/main/core/lib/i18n/README.md Illustrates complex ICU replacement for number formatting in JavaScript. Formats like `milliseconds`, `seconds`, `bytes`, `percent`, and `extendedPercent` are supported and automatically provide example values. A simple description string is sufficient. ```javascript const UIStrings = { /** Description of display value. */ displayValueText: 'Interactive at {timeInMs, number, seconds} s', }; ``` -------------------------------- ### Configure and Initialize GCP Lighthouse Collection Source: https://github.com/googlechrome/lighthouse/blob/main/core/scripts/gcp-collection/README.md Environment variables used to configure the Lighthouse collection process, including target git references, run counts, and project settings. These variables should be exported in the shell session before executing the fleet creation script. ```bash export TARGET_GIT_REF=<a lighthouse git ref that has been pushed> export TARGET_RUNS=<a number> export LIGHTHOUSE_FLAGS=... export LIGHTHOUSE_COLLECTION_GCLOUD_PROJECT=<project name> bash core/scripts/gcp-collection/fleet-create.sh path/to/your/url/list.txt ```