### 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 "