Skip to content

Commit 0ed011d

Browse files
authored
Merge pull request #195 from BeAPI/feat/cwv-baseline
perf(theme): add a core web vitals baseline
2 parents 1df4617 + 301b939 commit 0ed011d

15 files changed

Lines changed: 911 additions & 112 deletions

File tree

‎README.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,3 +176,50 @@ Sera nommé :
176176
```bash
177177
styles-blocks-coreParagraph.json
178178
```
179+
180+
## Core Web Vitals
181+
182+
### Ce que le thème fournit
183+
184+
- **Image LCP** : passez `'is_lcp' => true` dans les réglages de `get_the_image()` pour l’image principale au-dessus de la ligne de flottaison (hero, couverture). Cela retire `loading="lazy"` et ajoute `fetchpriority="high"`. Définissez `decoding` dans `$attributes` uniquement si une mesure le justifie (ex. WebPageTest). Une seule image par page. Par défaut `is_lcp => false` (opt-in).
185+
186+
```php
187+
the_image( $image_id, [ 'alt' => '' ], [ 'size' => 'hero', 'is_lcp' => true ] );
188+
```
189+
190+
- **ARI (Advanced Responsive Images)** : sur les projets avec ARI, ne pas activer `is_lcp` sur les images déjà gérées par ARI (taille / `data-location` au bon format). ARI pilote la priorité et le lazy-load ; `is_lcp` sur la même image est redondant ou incompatible. Réserver `is_lcp` aux projets sans ARI, ou valider manuellement (page hero avec ARI, sans `is_lcp`).
191+
192+
- **Images décoratives (`alt=""`)** — même objectif, deux helpers selon la source :
193+
- **Médiathèque** (`the_image` / `get_the_image`) : passez `'alt' => ''` explicitement si l’image est décorative. Sinon WordPress reprend l’alt saisi dans le BO. Omettre la clé `alt` n’est pas équivalent à `alt=""`.
194+
- **Fichiers buildés** dans `dist/` (`the_theme_static_image` / `get_theme_static_image_markup`) : décoratif par défaut (`alt=""` si vous ne passez pas `alt`). Indiquez un texte d’alt si l’image porte du sens (ex. logo + nom du site). Ne pas utiliser `the_image` pour ces fichiers (pas d’ID attachment).
195+
- **Images statiques du thème** (placeholders, illustrations dans `dist/`) : le helper statique ajoute aussi `width` et `height` via `dist/image-dimensions.json` (`imageDimensions`, généré au build) pour limiter le CLS, sans lecture disque répétée lorsque le manifeste est présent. Hors manifeste : une lecture par chemin et par requête.
196+
197+
```php
198+
// Média (décoratif)
199+
the_image( $image_id, [ 'alt' => '', 'class' => 'card__thumb' ], [ 'size' => 'card' ] );
200+
201+
// Asset dist/ (décoratif par défaut)
202+
the_theme_static_image( 'dist/images/placeholder.svg', [ 'class' => 'card__image', 'loading' => 'lazy' ] );
203+
204+
// Asset dist/ (alt porteur de sens)
205+
the_theme_static_image( 'dist/images/logo.svg', [ 'alt' => get_bloginfo( 'name' ), 'class' => 'header__logo' ] );
206+
```
207+
208+
- **Preload des polices** : opt-in, uniquement pour les polices rendues au premier affichage. Indiquez le chemin **après build** (ex. polices Fontsource ou custom dans `dist/fonts/`, en `.woff2`). Sur un thème bloc, ne préchargez que les fichiers réellement utilisés au premier rendu (cohérents avec `theme.json`).
209+
210+
```php
211+
add_filter( 'bea_theme_framework_preload_fonts', fn() => [ 'dist/fonts/my-font-regular.woff2' ] );
212+
```
213+
214+
- **JS** : `Animation` s’appuie sur `IntersectionObserver` (pas de boucle au scroll). `deferInitialization` est exposé sur `window.beapi.utils` pour exécuter du code non critique lorsque le navigateur est inactif (INP).
215+
216+
### Ce que chaque projet doit encore configurer
217+
218+
Cela dépend de l’hébergement, des extensions et du contenu ; ce n’est donc pas inclus dans le thème :
219+
220+
- Cache de page et réglages WP Rocket (suppression du CSS inutilisé, différer / retarder le JS et leurs exclusions, exclusions du lazyload pour l’image LCP, preconnect limités aux tiers chargés tôt).
221+
- `robots.txt` (endpoints techniques et AJAX) et en-têtes `Cache-Control` pour les assets statiques.
222+
- Réglages du plugin SEO : URLs canoniques sur pagination personnalisée, doublons de données structurées.
223+
- Polices : sous-ensemble des fichiers aux graisses et glyphes réellement utilisés, suppression des fichiers inutiles (italiques, graisses supplémentaires).
224+
- Intégrations tierces (vidéos, formulaires, webinars) : chargement à l’interaction ou à l’entrée dans le viewport.
225+
- Assets des extensions : retirer les scripts et styles front (dequeue) sur les pages qui ne les utilisent pas.

‎config/plugins.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const WebpackThemeJsonPlugin = require('./webpack-theme-json-plugin');
1414
const WatchedGlobEntriesPlugin = require('webpack-watched-glob-entries-plugin');
1515
const SpriteHashPlugin = require('./webpack-sprite-hash-plugin');
1616
const WebpackIconFilesPlugin = require('./webpack-icon-files-plugin');
17+
const WebpackStaticImageDimensionsPlugin = require('./webpack-static-image-dimensions-plugin');
1718

1819
module.exports = {
1920
get(mode) {
@@ -74,6 +75,7 @@ module.exports = {
7475
new WebpackPHPManifestPlugin({
7576
output: 'assets',
7677
}),
78+
new WebpackStaticImageDimensionsPlugin(),
7779
new RemoveEmptyScriptsPlugin()
7880
);
7981

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
const fs = require('fs')
2+
const path = require('path')
3+
const { imageSizeFromFile } = require('image-size/fromFile')
4+
5+
const IMAGE_EXT_PATTERN = /\.(png|jpe?g|gif|svg|webp|avif)$/i
6+
7+
/**
8+
* Parse intrinsic SVG dimensions (width/height attributes, then viewBox).
9+
*
10+
* @param {string} contents SVG file contents.
11+
* @return {{ width: number, height: number }|null}
12+
*/
13+
function getSvgDimensionsFromContents(contents) {
14+
if (!contents) {
15+
return null
16+
}
17+
18+
const widthMatch = contents.match(/\bwidth="(\d+(?:\.\d+)?)"/)
19+
const heightMatch = contents.match(/\bheight="(\d+(?:\.\d+)?)"/)
20+
21+
if (widthMatch && heightMatch) {
22+
return {
23+
width: Math.round(Number(widthMatch[1])),
24+
height: Math.round(Number(heightMatch[1])),
25+
}
26+
}
27+
28+
const viewBoxMatch = contents.match(/\bviewBox="[\d.\s-]+?\s+([\d.]+)\s+([\d.]+)"/)
29+
30+
if (viewBoxMatch) {
31+
return {
32+
width: Math.max(1, Math.round(Number(viewBoxMatch[1]))),
33+
height: Math.max(1, Math.round(Number(viewBoxMatch[2]))),
34+
}
35+
}
36+
37+
return null
38+
}
39+
40+
/**
41+
* Read width/height from a built image file under dist/.
42+
*
43+
* @param {string} filePath Absolute path to the image file.
44+
* @return {Promise<{ width: number, height: number }|null>}
45+
*/
46+
async function getImageDimensions(filePath) {
47+
if (!fs.existsSync(filePath)) {
48+
return null
49+
}
50+
51+
if (/\.svg$/i.test(filePath)) {
52+
const contents = fs.readFileSync(filePath, 'utf8')
53+
return getSvgDimensionsFromContents(contents)
54+
}
55+
56+
try {
57+
const dimensions = await imageSizeFromFile(filePath)
58+
59+
if (!dimensions.width || !dimensions.height) {
60+
return null
61+
}
62+
63+
return {
64+
width: dimensions.width,
65+
height: dimensions.height,
66+
}
67+
} catch (error) {
68+
return null
69+
}
70+
}
71+
72+
/**
73+
* Webpack plugin: write static image dimensions to a JSON manifest under dist/.
74+
*/
75+
class WebpackStaticImageDimensionsPlugin {
76+
constructor(options = {}) {
77+
this.options = {
78+
outputPath: 'dist',
79+
manifestFile: 'image-dimensions.json',
80+
imagesSubdir: 'images',
81+
...options,
82+
}
83+
}
84+
85+
apply(compiler) {
86+
compiler.hooks.afterEmit.tapAsync('WebpackStaticImageDimensionsPlugin', async (compilation, callback) => {
87+
try {
88+
const context = compiler.options.context
89+
const outputPath = path.resolve(context, this.options.outputPath)
90+
const manifestPath = path.join(outputPath, this.options.manifestFile)
91+
const imageDimensions = {}
92+
93+
const assets = compilation.getAssets()
94+
95+
for (const asset of assets) {
96+
if (!asset.name.startsWith(`${this.options.imagesSubdir}/`) || !IMAGE_EXT_PATTERN.test(asset.name)) {
97+
continue
98+
}
99+
100+
const filePath = path.join(outputPath, asset.name)
101+
const dimensions = await getImageDimensions(filePath)
102+
103+
if (!dimensions) {
104+
continue
105+
}
106+
107+
const themeRelativePath = `dist/${asset.name.replace(/\\/g, '/')}`
108+
imageDimensions[themeRelativePath] = dimensions
109+
}
110+
111+
const manifest = {
112+
imageDimensions,
113+
}
114+
115+
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
116+
callback()
117+
} catch (error) {
118+
callback(error)
119+
}
120+
})
121+
}
122+
}
123+
124+
module.exports = WebpackStaticImageDimensionsPlugin

0 commit comments

Comments
 (0)