HowTo-Components are a set of elements which demonstrate Custom Element and Shadow DOM best practices. These elements are not intended to be used in production, but are instead presented as a teaching aide to help map best practice suggestions to actual implementations.
Learn more ``` -------------------------------- ### BufferLoader Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webaudio-intro/index.md Demonstrates how to use a BufferLoader class to load multiple audio files asynchronously and play them back simultaneously once loaded. This is useful for pre-loading sound assets in applications. ```js window.onload = init; var context; var bufferLoader; function init() { context = new AudioContext(); bufferLoader = new BufferLoader( context, [ '../sounds/hyper-reality/br-jam-loop.wav', '../sounds/hyper-reality/laughter.wav', ], finishedLoading ); bufferLoader.load(); } function finishedLoading(bufferList) { // Create two sources and play them both together. var source1 = context.createBufferSource(); var source2 = context.createBufferSource(); source1.buffer = bufferList[0]; source2.buffer = bufferList[1]; source1.connect(context.destination); source2.connect(context.destination); source1.noteOn(0); source2.noteOn(0); } ``` -------------------------------- ### Obtendo informações do dispositivo com JavaScript Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/pt/progressive-web-apps/define-install-strategy/index.md Este snippet demonstra como usar APIs JavaScript como navigator.hardwareConcurrency, navigator.deviceMemory e navigator.connection para obter informações sobre a CPU, memória e status da rede de um dispositivo. Essas informações podem ser usadas para categorizar dispositivos e adaptar a experiência do usuário. ```javascript const deviceCategory = req.get('Device-Memory') < 1 ? 'lite' : 'full'; ``` -------------------------------- ### Chrome DevTools Network Panel Usage Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/performance-audit-tools/index.md Instructions on using the Chrome DevTools network panel for performance auditing, including getting started guides and saving profile data. ```html Get Started Guide save profile data disable the browser cache clear Cache API storage ``` -------------------------------- ### Handling PWA Installation Prompt Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/learn/pwa/installation-prompt/index.md This JavaScript code snippet demonstrates how to capture the `beforeinstallprompt` event, display a custom install UI, and handle the user's choice (accepted or dismissed). It also shows how to reset the deferred prompt after use. ```js installButton.addEventListener('click', async () => { // deferredPrompt is a global variable we've been using in the sample to capture the `beforeinstallevent` deferredPrompt.prompt(); // Find out whether the user confirmed the installation or not const { outcome } = await deferredPrompt.userChoice; // The deferredPrompt can only be used once. deferredPrompt = null; // Act on the user's choice if (outcome === 'accepted') { console.log('User accepted the install prompt.'); } else if (outcome === 'dismissed') { console.log('User dismissed the install prompt'); } }); ``` -------------------------------- ### Usability Review Examples Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/handbook/reviews/index.md Examples of content that should undergo usability reviews, including codelabs, tooling guides, and API guides. These examples illustrate the practical application of the review process. ```htmlCodelabs like [Configure HTTP caching behavior](/codelab-http-cache/)
Tooling guides like [Replace animated GIFs with video](/replace-gifs-with-videos/)
API guides like [Getting started with Trust Tokens](/trust-tokens/)
``` -------------------------------- ### webpkgserver Successful Startup Logs Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/fast/signed-exchanges-webpackager/index.md Example log messages indicating a successful startup of the webpkgserver, including the listening address, OCSP retrieval status, and cache directory. ```shell Listening at 127.0.0.1:8080 Successfully retrieved valid OCSP. Writing to cache in /private/tmp/webpkg ``` -------------------------------- ### Start Local Development Server Source: https://github.com/googlechrome/web.dev/blob/main/README.md Starts a local development server to preview the website. Changes to assets will trigger automatic rebuilds. Access the site at http://localhost:8080/. ```bash npm run dev ``` -------------------------------- ### CSS circle() shape with positioned center Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/shapes-getting-started/index.md This example shows how to position the center of the `circle()` shape using coordinates. Here, the center is set to the origin (0 0) of the element's coordinate system. ```css .element{ shape-outside: circle(50% at 0 0); } ``` -------------------------------- ### JavaScript Setup for Convolution Kernel Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webgl-fundamentals/index.md This JavaScript code demonstrates how to get the uniform location for the kernel array in GLSL and how to set its values. It shows an example of an edge detection kernel and passing it to the shader using `gl.uniform1fv`. ```javascript var kernelLocation = gl.getUniformLocation(program, "u_kernel[0]"); var edgeDetectKernel = [ -1, -1, -1, -1, 8, -1, -1, -1, -1 ]; gl.uniform1fv(kernelLocation, edgeDetectKernel); ``` -------------------------------- ### インストールボタンのクリックを処理する Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/ja/progressive-web-apps/codelab-make-installable/index.md このコードは、インストールボタンのクリックイベントを処理し、保存された `beforeinstallprompt` イベントで `prompt()` を呼び出してインストールプロンプトを表示します。また、プロンプトの結果をログに記録し、インストールボタンを非表示にします。 ```js butInstall.addEventListener('click', async () => { console.log('👍', 'butInstall-clicked'); const promptEvent = window.deferredPrompt; if (!promptEvent) { // デファーされたプロンプトは使用できません。 return; } // インストールプロンプトを表示する。 promptEvent.prompt(); // 結果をログに記録する const result = await promptEvent.userChoice; console.log('👍', 'userChoice', result); // デファーされたプロンプトの変数をリセット。 // prompt() は1回しか呼び出せません。 window.deferredPrompt = null; // インストールボタンを非表示にする。 divInstall.classList.toggle('hidden', true); }); ``` -------------------------------- ### Triggering PWA Installation Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/progressive-web-apps/promote-install/index.md This snippet demonstrates how to trigger the PWA installation flow. It involves listening for the `beforeinstallprompt` event and then showing a UI element (like a button) that, when clicked, displays the install prompt. This is a core mechanism for custom PWA installation experiences. ```javascript let deferredPrompt; window.addEventListener('beforeinstallprompt', (e) => { // Prevent Chrome 67 and earlier from automatically showing the prompt e.preventDefault(); // Stash the event so it can be triggered later. deferredPrompt = e; // Update UI to notify the user they can add to home screen // For example, add a "Install" button to your web app's UI. showInstallButton(); }); async function installPWA() { // Show the prompt deferredPrompt.prompt(); // Wait for the user to respond to the prompt const { outcome } = await deferredPrompt.userChoice; // Optionally, send the result to analytics console.log(`User response to the install prompt: ${outcome}`); // We've used the prompt, and may not need it again. If the user has // dismissed the prompt, then deferredPrompt will be null. deferredPrompt = null; } function showInstallButton() { // Logic to display an install button or other UI element // For example: const installButton = document.getElementById('install-button'); if (installButton) { installButton.style.display = 'block'; installButton.addEventListener('click', installPWA); } } ``` -------------------------------- ### Three.js Scene Setup Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/three-intro/index.md Initializes a WebGL renderer, a perspective camera, and a scene using the Three.js library. It sets up basic scene dimensions, camera attributes, and attaches the renderer's output to a DOM element. ```js var WIDTH = 400, HEIGHT = 300; var VIEW_ANGLE = 45, ASPECT = WIDTH / HEIGHT, NEAR = 0.1, FAR = 10000; var $container = $('#container'); var renderer = new THREE.WebGLRenderer(); var camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR ); var scene = new THREE.Scene(); camera.position.z = 300; renderer.setSize(WIDTH, HEIGHT); $container.append(renderer.domElement); ``` -------------------------------- ### Animating Polygon Shape Outside Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/shapes-getting-started/index.md Illustrates animating a `polygon()` shape with CSS transitions. This example transitions a rectangle shape to a triangle shape by adjusting the vertices, ensuring the same number of vertices are used in both states. ```css .element{ /* four vertices (looks like rectangle) */ shape-outside: polygon(0 0, 100% 0, 100% 100%, 0 100%); transition: shape-outside 1s; } .element:hover{ /* four vertices, but second and third overlap (looks like triangle) */ shape-outside: polygon(0 0, 100% 50%, 100% 50%, 0 100%); } ``` -------------------------------- ### App Shortcuts Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/learn/pwa/installation/index.md Shows how to define contextual menus for PWA icons using the App Shortcuts feature in the Web App Manifest. This allows users to quickly access common actions within the PWA directly from the icon. ```json { "name": "My PWA", "icons": [ { "src": "/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" } ], "shortcuts": [ { "name": "New Note", "short_name": "New Note", "url": "/new-note", "icons": [ { "src": "/icons/new-note-icon.png", "sizes": "192x192", "type": "image/png" } ] } ] } ``` -------------------------------- ### Lighthouse CI Docker Setup Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/lighthouse-evolution-cds-2019/index.md This snippet provides information on setting up the Lighthouse CI server using a Docker image for instant deployment. It links to a recipe for a Docker server setup, indicating a streamlined approach to getting Lighthouse CI running. ```html You can install the Lighthouse CI server on-premise or use a [docker image for instant setup](https://github.com/GoogleChrome/lighthouse-ci/blob/master/docs/recipes/docker-server/README.md). ``` -------------------------------- ### CSS Shape Margin Example Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/shapes-getting-started/index.md Demonstrates the use of `shape-outside` with a circle and `shape-margin` to create spacing around the shape. The `shape-margin` property adds space around the defined shape, influencing how content flows. ```css .element{ shape-outside: circle(40%); shape-margin: 1em; float: left; } ``` -------------------------------- ### Animating Circle Shape Outside Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/shapes-getting-started/index.md Shows how to animate the `shape-outside` property for a circle using CSS transitions. This example transitions the circle's radius from 30% to 50% on hover, creating a visual animation. ```css .element{ shape-outside: circle(30%); transition: shape-outside 1s; float: left; } .element:hover{ shape-outside: circle(50%); } ``` -------------------------------- ### Escuchar el evento beforeinstallprompt Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/es/progressive-web-apps/codelab-make-installable/index.md Este código agrega un manejador de eventos al objeto `window` para el evento `beforeinstallprompt`. Cuando se activa, evita la barra de información mini, almacena el evento para su uso posterior y muestra un botón de instalación al usuario. ```js window.addEventListener('beforeinstallprompt', (event) => { // Prevent the mini-infobar from appearing on mobile. event.preventDefault(); console.log('👍', 'beforeinstallprompt', event); // Stash the event so it can be triggered later. window.deferredPrompt = event; // Remove the 'hidden' class from the install button container. divInstall.classList.toggle('hidden', false); }); ``` -------------------------------- ### 인앱 설치 흐름 시작 Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/ko/progressive-web-apps/customize-install/index.md 사용자가 앱을 설치하기 위해 클릭할 수 있는 버튼 또는 기타 인터페이스 요소를 제공합니다. 요소를 클릭하면 저장된 `beforeinstallprompt` 이벤트(`deferredPrompt` 변수에 저장됨)에서 `prompt()`를 호출하여 사용자에게 PWA를 설치할지 확인하는 모달 설치 대화 상자를 표시합니다. ```js buttonInstall.addEventListener('click', async () => { // Hide the app provided install promotion hideInstallPromotion(); // Show the install prompt deferredPrompt.prompt(); // Wait for the user to respond to the prompt const { outcome } = await deferredPrompt.userChoice; // Optionally, send analytics event with outcome of user choice console.log(`User response to the install prompt: ${outcome}`); // We've used the prompt, and can't use it again, throw it away deferredPrompt = null; }); ``` -------------------------------- ### Basic CSS circle() shape Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/shapes-getting-started/index.md This example demonstrates how to use the `circle()` function with `shape-outside` to create a circular path for content wrapping. The radius is set to 50%, making it responsive to the element's dimensions. ```css .element{ shape-outside: circle(50%); width: 300px; height: 300px; float: left; } ``` -------------------------------- ### Dynamic Server-Side Hints - Blog Route Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/migrate-to-ua-ch/index.md Example of response headers for a '/blog' route, specifying a set of Client Hints. ```text Accept-CH: Sec-CH-UA-Mobile, Sec-CH-UA-Platform, Sec-CH-UA ``` -------------------------------- ### Create and Configure Low-Pass Filter Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/blog/webaudio-intro/index.md This snippet demonstrates how to create a BiquadFilterNode, connect it within an audio graph, set its type to low-pass, and define the cutoff frequency. It's a fundamental example of applying a filter effect. ```js var context = new AudioContext(); var source = context.createBufferSource(); // Assume source is already created and has audio data // Create the filter var filter = context.createBiquadFilter(); // Create the audio graph. source.connect(filter); filter.connect(context.destination); // Create and specify parameters for the low-pass filter. filter.type = 0; // Low-pass filter. See BiquadFilterNode docs filter.frequency.value = 440; // Set cutoff to 440 HZ // Playback the sound. source.start(0); ``` -------------------------------- ### Copy webpkgserver.example.toml Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/en/fast/signed-exchanges-webpackager/index.md Copies the example webpkgserver.toml file to a new file named webpkgserver.toml, which will be used for configuration. ```shell cp ./webpkgserver.example.toml ./webpkgserver.toml ``` -------------------------------- ### Manejar el evento beforeinstallprompt para la instalación en la aplicación Source: https://github.com/googlechrome/web.dev/blob/main/src/site/content/es/progressive-web-apps/customize-install/index.md Este snippet muestra cómo manejar el evento `beforeinstallprompt` para permitir a los usuarios instalar la PWA. Captura la elección del usuario después de que se muestra el prompt de instalación y limpia la variable `deferredPrompt`. ```js buttonInstall.addEventListener('click', async () => { // Esconde la información promotora de la instalación hideInstallPromotion(); // Muestre el mensaje de instalación deferredPrompt.prompt(); // Espera a que el usuario responda al mensaje const { outcome } = await deferredPrompt.userChoice; // De manera opcional, envía analíticos del resultado que eligió el usuario console.log(`User response to the install prompt: ${outcome}`); // Como ya usamos el mensaje, no lo podemos usar de nuevo, este es descartado deferredPrompt = null; }); ```