Skip to content

Commit e245d85

Browse files
perf(theme): read static image dimensions from build manifest
Write image width/height into dist/image-dimensions.json at build time and resolve them from the memoized manifest at runtime to avoid N+1 filesystem I/O in loops. Keep a per-request filesystem fallback for assets outside the build. Drop default decoding=sync on is_lcp and document manifest-based CLS helpers. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent d2eea3e commit e245d85

5 files changed

Lines changed: 270 additions & 7 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -181,14 +181,14 @@ styles-blocks-coreParagraph.json
181181

182182
### Ce que le thème fournit
183183

184-
- **Image LCP** : passer `'is_lcp' => true` dans les réglages de `get_the_image()` pour l'image principale au-dessus de la ligne de flottaison (hero, cover). Cela retire `loading="lazy"` et ajoute `fetchpriority="high"` et `decoding="sync"`. Une seule image par page.
184+
- **Image LCP** : passer `'is_lcp' => true` dans les réglages de `get_the_image()` pour l'image principale au-dessus de la ligne de flottaison (hero, cover). Cela retire `loading="lazy"` et ajoute `fetchpriority="high"`. Définir `decoding` explicitement dans `$attributes` si une mesure (ex. WebPageTest) le justifie. Une seule image par page.
185185
186186
```php
187187
the_image( $image_id, [ 'alt' => '' ], [ 'size' => 'hero', 'is_lcp' => true ] );
188188
```
189189
190190
- **Images décoratives** : passer `'alt' => ''` pour produire `alt=""`. Omettre l'attribut n'est pas équivalent pour les technologies d'assistance.
191-
- **Images statiques du thème** (logos, placeholders, illustrations de `dist/`) : `get_theme_static_image_markup()` / `the_theme_static_image()`. `width` et `height` sont lus dans le fichier (SVG ou raster) pour limiter le CLS.
191+
- **Images statiques du thème** (logos, placeholders, illustrations de `dist/`) : `get_theme_static_image_markup()` / `the_theme_static_image()`. `width` et `height` proviennent de `dist/image-dimensions.json` (`imageDimensions`, généré au build) pour limiter le CLS sans lecture disque répétée. Hors manifeste : une lecture par chemin et par requête.
192192

193193
```php
194194
the_theme_static_image( 'dist/images/placeholder.svg', [ 'class' => 'card__image', 'loading' => 'lazy' ] );

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

‎inc/Helpers/Formatting/Image.php‎

Lines changed: 66 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
<?php
22
namespace BEA\Theme\Framework\Helpers\Formatting\Image;
33

4+
use BEA\Theme\Framework\Framework;
5+
46
/**
57
* @usage BEA\Theme\Framework\Helpers\Formatting\Image\get_the_image( 1, [ 'data-location' => 'image-size' ] );
68
*
@@ -32,8 +34,8 @@
3234
* @type string $after Optional. Markup to append to the image. Default empty.
3335
* @type boolean $default Optional. If WP image does not exists, display a default image.
3436
* @type boolean $is_lcp Optional. When true, applies LCP-friendly attributes
35-
* (loading omitted, fetchpriority=high, decoding=sync)
36-
* unless decoding is already set in $attributes.
37+
* (loading omitted, fetchpriority=high).
38+
* decoding may be set explicitly in $attributes.
3739
*
3840
* }
3941
*
@@ -71,7 +73,6 @@ function get_the_image( int $image_id, array $attributes, array $settings = [] )
7173
// Always win over caller/WP defaults: the LCP image must not be lazy-loaded.
7274
$attributes['loading'] = false;
7375
$attributes['fetchpriority'] = 'high';
74-
$attributes['decoding'] = $attributes['decoding'] ?? 'sync';
7576
}
7677

7778
// Never combine fetchpriority=high with loading=lazy (undefined browser behavior).
@@ -143,18 +144,78 @@ function the_image( int $image_id, array $attributes, array $settings = [] ): vo
143144
echo get_the_image( $image_id, $attributes, $settings );
144145
}
145146

147+
/**
148+
* Resolve the public URI for a static theme asset without redundant filesystem checks.
149+
*
150+
* @param string $relative_theme_path Path relative to the theme root.
151+
*
152+
* @return string
153+
*/
154+
function get_theme_static_image_uri( string $relative_theme_path ): string {
155+
static $uri_cache = [];
156+
157+
$relative_theme_path = ltrim( $relative_theme_path, '/' );
158+
159+
if ( isset( $uri_cache[ $relative_theme_path ] ) ) {
160+
return $uri_cache[ $relative_theme_path ];
161+
}
162+
163+
if ( get_stylesheet() === get_template() ) {
164+
$uri = get_stylesheet_directory_uri() . '/' . $relative_theme_path;
165+
$uri = apply_filters( 'theme_file_uri', $uri, $relative_theme_path );
166+
} else {
167+
$uri = get_theme_file_uri( $relative_theme_path );
168+
}
169+
170+
$uri_cache[ $relative_theme_path ] = $uri;
171+
172+
return $uri;
173+
}
174+
146175
/**
147176
* Read intrinsic dimensions from a static file under the active theme directory.
148177
*
178+
* Uses build-time dimensions from `dist/image-dimensions.json` when available; otherwise reads the file once per request.
179+
*
149180
* @usage BEA\Theme\Framework\Helpers\Formatting\Image\get_theme_static_image_dimensions( 'dist/images/logo.svg' );
150181
*
151182
* @param string $relative_theme_path Path relative to the theme root (e.g. dist/images/logo.svg).
152183
*
153184
* @return array{width:int,height:int}|null Null when the file is missing or dimensions cannot be read.
154185
*/
155186
function get_theme_static_image_dimensions( string $relative_theme_path ): ?array {
187+
static $cache = [];
188+
156189
$relative_theme_path = ltrim( $relative_theme_path, '/' );
157-
$file_path = get_theme_file_path( $relative_theme_path );
190+
191+
if ( array_key_exists( $relative_theme_path, $cache ) ) {
192+
return $cache[ $relative_theme_path ];
193+
}
194+
195+
$assets = Framework::get_container()->get_service( 'assets' );
196+
$from_manifest = $assets->get_static_image_dimensions( $relative_theme_path );
197+
198+
if ( null !== $from_manifest ) {
199+
$cache[ $relative_theme_path ] = $from_manifest;
200+
201+
return $from_manifest;
202+
}
203+
204+
$from_filesystem = read_theme_static_image_dimensions_from_filesystem( $relative_theme_path );
205+
$cache[ $relative_theme_path ] = $from_filesystem;
206+
207+
return $from_filesystem;
208+
}
209+
210+
/**
211+
* Fallback: read intrinsic dimensions from the theme filesystem.
212+
*
213+
* @param string $relative_theme_path Path relative to the theme root.
214+
*
215+
* @return array{width:int,height:int}|null
216+
*/
217+
function read_theme_static_image_dimensions_from_filesystem( string $relative_theme_path ): ?array {
218+
$file_path = get_theme_file_path( $relative_theme_path );
158219

159220
if ( ! is_string( $file_path ) || '' === $file_path || ! is_readable( $file_path ) ) {
160221
return null;
@@ -214,7 +275,7 @@ function get_theme_static_image_markup( string $relative_theme_path, array $attr
214275
$attributes = wp_parse_args(
215276
$attributes,
216277
[
217-
'src' => get_theme_file_uri( $relative_theme_path ),
278+
'src' => get_theme_static_image_uri( $relative_theme_path ),
218279
'alt' => '',
219280
]
220281
);

‎inc/Services/Assets.php‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,71 @@ private function register_partial_js_assets( $class_name, $path_from_theme_root,
463463
);
464464
}
465465

466+
/**
467+
* Return intrinsic dimensions for a static theme image from the build manifest.
468+
*
469+
* @param string $relative_theme_path Path relative to the theme root (e.g. dist/images/logo.svg).
470+
*
471+
* @return array{width:int,height:int}|null Null when dimensions are not in the manifest.
472+
*/
473+
public function get_static_image_dimensions( string $relative_theme_path ): ?array {
474+
$relative_theme_path = ltrim( $relative_theme_path, '/' );
475+
$dimensions_map = $this->get_static_image_dimensions_manifest();
476+
477+
if ( empty( $dimensions_map ) ) {
478+
return null;
479+
}
480+
481+
$dimensions = $dimensions_map[ $relative_theme_path ] ?? null;
482+
483+
if ( ! is_array( $dimensions ) ) {
484+
return null;
485+
}
486+
487+
$width = isset( $dimensions['width'] ) ? (int) $dimensions['width'] : 0;
488+
$height = isset( $dimensions['height'] ) ? (int) $dimensions['height'] : 0;
489+
490+
if ( $width <= 0 || $height <= 0 ) {
491+
return null;
492+
}
493+
494+
return [
495+
'width' => $width,
496+
'height' => $height,
497+
];
498+
}
499+
500+
/**
501+
* Read and decode `dist/image-dimensions.json` once per request.
502+
*
503+
* @return array<string, array{width:int,height:int}>
504+
*/
505+
private function get_static_image_dimensions_manifest(): array {
506+
static $dimensions_map = null;
507+
508+
if ( null !== $dimensions_map ) {
509+
return $dimensions_map;
510+
}
511+
512+
$dimensions_map = [];
513+
$manifest_path = get_theme_file_path( self::BUILD_DIR . '/image-dimensions.json' );
514+
515+
if ( ! is_readable( $manifest_path ) ) {
516+
return $dimensions_map;
517+
}
518+
519+
$json = file_get_contents( $manifest_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
520+
$data = json_decode( $json, true );
521+
522+
if ( ! is_array( $data ) || empty( $data['imageDimensions'] ) || ! is_array( $data['imageDimensions'] ) ) {
523+
return $dimensions_map;
524+
}
525+
526+
$dimensions_map = $data['imageDimensions'];
527+
528+
return $dimensions_map;
529+
}
530+
466531
/**
467532
* Load assets manifest.
468533
*

0 commit comments

Comments
 (0)