Skip to content

Commit 1498fe6

Browse files
committed
perf(theme): cache static image dimensions in assets.json at build time
1 parent 21f2e50 commit 1498fe6

6 files changed

Lines changed: 258 additions & 16 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
# 5.5.0
22

3-
- Add `is_lcp` setting to `get_the_image()` (fetchpriority high, sync decoding, no lazy loading)
3+
- Add `is_lcp` setting to `get_the_image()` (fetchpriority high, no lazy loading; decoding is opt-in via attributes)
44
- Never output `fetchpriority="high"` together with `loading="lazy"` in image helpers
55
- Add `get_theme_static_image_markup()` helpers: static theme images get width/height (CLS) and keep `alt=""` for decorative images
6+
- Store static image dimensions in `dist/assets.json` at build time (`imageDimensions`) so runtime helpers avoid repeated filesystem I/O
67
- Lower the custom logo `fetchpriority` so it does not compete with the LCP image
78
- Add `bea_theme_framework_preload_fonts` filter (empty by default) to preload above-the-fold fonts
89
- Rewrite `Animation` with shared IntersectionObservers instead of a scroll loop (same options and callbacks)

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,14 +198,14 @@ yarn bundle-report
198198

199199
### What the theme provides
200200

201-
- **LCP image**: pass `'is_lcp' => true` in the settings of `get_the_image()` for the main above-the-fold image (hero, cover). It removes `loading="lazy"` and adds `fetchpriority="high"` and `decoding="sync"`. Use it on one image per page only.
201+
- **LCP image**: pass `'is_lcp' => true` in the settings of `get_the_image()` for the main above-the-fold image (hero, cover). It removes `loading="lazy"` and adds `fetchpriority="high"`. Set `decoding` explicitly in `$attributes` when you have measured that it helps (e.g. WebPageTest). Use it on one image per page only.
202202

203203
```php
204204
the_image( $image_id, [ 'alt' => '' ], [ 'size' => 'hero', 'is_lcp' => true ] );
205205
```
206206

207207
- **Decorative images**: pass `'alt' => ''` to output `alt=""`, so assistive technologies skip the image. Omitting `alt` is not equivalent.
208-
- **Static theme images** (logos, placeholders, illustrations from `dist/`): use `get_theme_static_image_markup()` / `the_theme_static_image()`. `width` and `height` are read from the file (SVG or raster) to avoid layout shifts (CLS).
208+
- **Static theme images** (logos, placeholders, illustrations from `dist/`): use `get_theme_static_image_markup()` / `the_theme_static_image()`. `width` and `height` come from `dist/assets.json` (`imageDimensions`, written at build time) to avoid layout shifts (CLS) without per-request filesystem reads. Files outside the build manifest fall back to a one-time read per path per request.
209209

210210
```php
211211
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
@@ -10,6 +10,7 @@ const DependencyExtractionWebpackPlugin = require('@wordpress/dependency-extract
1010
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
1111

1212
const WebpackImageSizesPlugin = require('./webpack-image-sizes-plugin')
13+
const WebpackStaticImageDimensionsPlugin = require('./webpack-static-image-dimensions-plugin')
1314
const WebpackThemeJsonPlugin = require('./webpack-theme-json-plugin')
1415
const SpriteHashPlugin = require('./webpack-sprite-hash-plugin')
1516

@@ -58,6 +59,7 @@ module.exports = {
5859
new WebpackManifestPlugin({
5960
fileName: 'assets.json',
6061
}),
62+
new WebpackStaticImageDimensionsPlugin(),
6163
]
6264

6365
if (mode === 'production') {
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
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: merge static image dimensions into dist/assets.json.
85+
*/
86+
class WebpackStaticImageDimensionsPlugin {
87+
constructor(options = {}) {
88+
this.options = {
89+
outputPath: 'dist',
90+
manifestFile: 'assets.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+
let manifest = {}
123+
124+
if (fs.existsSync(manifestPath)) {
125+
const raw = fs.readFileSync(manifestPath, 'utf8')
126+
const parsed = JSON.parse(raw)
127+
128+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
129+
manifest = parsed
130+
}
131+
}
132+
133+
manifest.imageDimensions = imageDimensions
134+
135+
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
136+
callback()
137+
} catch (error) {
138+
callback(error)
139+
}
140+
})
141+
}
142+
}
143+
144+
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/assets.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: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -140,45 +140,79 @@ public function get_min_file( string $type ): string {
140140

141141
switch ( $type ) {
142142
case 'css':
143-
$file = $assets['app.css'];
143+
$file = $assets['app.css'] ?? null;
144144
break;
145145
case 'editor.css':
146-
$file = $assets['editor.css'];
146+
$file = $assets['editor.css'] ?? null;
147147
break;
148148
case 'login':
149-
$file = $assets['login.css'];
149+
$file = $assets['login.css'] ?? null;
150150
break;
151151
case 'editor.js':
152-
$file = $assets['editor.js'];
152+
$file = $assets['editor.js'] ?? null;
153153
break;
154154
case 'js':
155-
$file = $assets['app.js'];
155+
$file = $assets['app.js'] ?? null;
156156
break;
157157
default:
158158
$file = null;
159159
break;
160160
}
161161

162162
// Custom type
163-
if ( ! empty( $assets[ $type ] ) ) {
163+
if ( null === $file && ! empty( $assets[ $type ] ) && is_string( $assets[ $type ] ) ) {
164164
$file = $assets[ $type ];
165165
}
166166

167-
if ( empty( $file ) ) {
167+
if ( empty( $file ) || ! is_string( $file ) ) {
168168
return '';
169169
}
170170

171171
return $file;
172172
}
173173

174+
/**
175+
* Return intrinsic dimensions for a static theme image from the build manifest.
176+
*
177+
* @param string $relative_theme_path Path relative to the theme root (e.g. dist/images/logo.svg).
178+
*
179+
* @return array{width:int,height:int}|null Null when dimensions are not in the manifest.
180+
*/
181+
public function get_static_image_dimensions( string $relative_theme_path ): ?array {
182+
$relative_theme_path = ltrim( $relative_theme_path, '/' );
183+
$manifest = $this->get_assets_manifest();
184+
185+
if ( empty( $manifest['imageDimensions'] ) || ! is_array( $manifest['imageDimensions'] ) ) {
186+
return null;
187+
}
188+
189+
$dimensions = $manifest['imageDimensions'][ $relative_theme_path ] ?? null;
190+
191+
if ( ! is_array( $dimensions ) ) {
192+
return null;
193+
}
194+
195+
$width = isset( $dimensions['width'] ) ? (int) $dimensions['width'] : 0;
196+
$height = isset( $dimensions['height'] ) ? (int) $dimensions['height'] : 0;
197+
198+
if ( $width <= 0 || $height <= 0 ) {
199+
return null;
200+
}
201+
202+
return [
203+
'width' => $width,
204+
'height' => $height,
205+
];
206+
}
207+
174208
/**
175209
* Read and decode the `dist/assets.json` manifest once per request.
176210
*
177211
* The manifest is requested several times per request (scripts registration,
178212
* `stylesheet_uri` filter, editor assets…): memoize the decoded content to
179213
* avoid repeated filesystem reads and JSON decoding.
180214
*
181-
* @return array<string, string> Manifest entries, or an empty array if unavailable/invalid.
215+
* @return array<string, mixed> Manifest entries, or an empty array if unavailable/invalid.
182216
*/
183217
private function get_assets_manifest(): array {
184218
static $manifest = null;

0 commit comments

Comments
 (0)