Skip to content

Commit 880d5d2

Browse files
perf(theme): add a core web vitals baseline
Give projects opt-in LCP images, sized static images, a low-priority logo, idle JS init, and scroll-free animations so new themes start closer to good CWV scores. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent ecb4312 commit 880d5d2

5 files changed

Lines changed: 415 additions & 57 deletions

File tree

‎README.md‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,43 @@ yarn bundle-report
196196

197197
## Core Web Vitals
198198

199+
### What the theme provides
200+
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.
202+
203+
```php
204+
the_image( $image_id, [ 'alt' => '' ], [ 'size' => 'hero', 'is_lcp' => true ] );
205+
```
206+
207+
- **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).
209+
210+
```php
211+
the_theme_static_image( 'dist/images/placeholder.svg', [ 'class' => 'card__image', 'loading' => 'lazy' ] );
212+
```
213+
214+
- **Custom logo**: gets `fetchpriority="low"` so it never competes with the real LCP image.
215+
- **Fonts preload**: opt-in, only for fonts rendered on first paint.
216+
217+
```php
218+
add_filter( 'bea_theme_framework_preload_fonts', fn() => [ 'dist/fonts/my-font-regular.woff2' ] );
219+
```
220+
221+
- **JS**: `Animation` relies on `IntersectionObserver` (no scroll loop). Use `deferInitialization()` from `src/js/utils` to run non-critical code when the browser is idle (INP).
222+
223+
### What each project still has to configure
224+
225+
These depend on the hosting, plugins and content, so they are not part of the theme:
226+
227+
- Page cache and WP Rocket settings (Remove Unused CSS, defer / delay JS and their exclusions, lazyload exclusions for the LCP image, preconnect hints limited to the third parties loaded early).
228+
- `robots.txt` (technical and AJAX endpoints) and `Cache-Control` headers for static assets.
229+
- SEO plugin settings: canonical URLs on custom pagination, structured data duplicates.
230+
- Fonts: subset files to the weights and glyphs actually used, drop unused files (italics, extra weights).
231+
- Third-party embeds (videos, forms, webinars): load them on interaction or when they enter the viewport.
232+
- Plugin assets: dequeue front scripts and styles on pages that do not use them.
233+
234+
## WordPress Editor (Gutenberg)
235+
199236
### Ce que le thème fournit
200237

201238
- **Image LCP** : passez `'is_lcp' => true` dans les réglages de `get_the_image()` pour l’image principale above-the-fold (hero, couverture). Cela retire `loading="lazy"` et ajoute `fetchpriority="high"` et `decoding="sync"`. À utiliser sur une seule image par page.

‎inc/Helpers/Formatting/Image.php‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
* @type string $alt Image description for the alt attribute.
1818
* @type string $srcset The 'srcset' attribute value.
1919
* @type string $sizes The 'sizes' attribute value.
20+
* @type string $fetchpriority The 'fetchpriority' attribute value (e.g. 'high', 'low').
21+
* @type string $decoding The 'decoding' attribute value (e.g. 'sync', 'async').
2022
* @type string|false $loading The 'loading' attribute value. Passing a value of false
2123
* will result in the attribute being omitted for the image.
2224
* Defaults to 'lazy', depending on wp_lazy_loading_enabled().
@@ -29,6 +31,9 @@
2931
* @type string $before Optional. Markup to prepend to the image. Default empty.
3032
* @type string $after Optional. Markup to append to the image. Default empty.
3133
* @type boolean $default Optional. If WP image does not exists, display a default image.
34+
* @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.
3237
*
3338
* }
3439
*
@@ -56,11 +61,24 @@ function get_the_image( int $image_id, array $attributes, array $settings = [] )
5661
'before' => '',
5762
'after' => '',
5863
'default' => false,
64+
'is_lcp' => false,
5965
]
6066
);
6167

6268
$settings = apply_filters( 'bea_theme_framework_the_image_settings', $settings, $image_id, $attributes );
6369

70+
if ( ! empty( $settings['is_lcp'] ) ) {
71+
// Always win over caller/WP defaults: the LCP image must not be lazy-loaded.
72+
$attributes['loading'] = false;
73+
$attributes['fetchpriority'] = 'high';
74+
$attributes['decoding'] = $attributes['decoding'] ?? 'sync';
75+
}
76+
77+
// Never combine fetchpriority=high with loading=lazy (undefined browser behavior).
78+
if ( isset( $attributes['fetchpriority'] ) && 'high' === $attributes['fetchpriority'] ) {
79+
$attributes['loading'] = false;
80+
}
81+
6482
if ( 0 === $image_id && ! $settings['default'] ) {
6583
return '';
6684
}
@@ -102,6 +120,8 @@ function get_the_image( int $image_id, array $attributes, array $settings = [] )
102120
* @type string $alt Image description for the alt attribute.
103121
* @type string $srcset The 'srcset' attribute value.
104122
* @type string $sizes The 'sizes' attribute value.
123+
* @type string $fetchpriority The 'fetchpriority' attribute value (e.g. 'high', 'low').
124+
* @type string $decoding The 'decoding' attribute value (e.g. 'sync', 'async').
105125
* @type string|false $loading The 'loading' attribute value. Passing a value of false
106126
* will result in the attribute being omitted for the image.
107127
* Defaults to 'lazy', depending on wp_lazy_loading_enabled().
@@ -113,6 +133,7 @@ function get_the_image( int $image_id, array $attributes, array $settings = [] )
113133
* @type string $size Optional. The 'sizes' attribute value.
114134
* @type string $before Optional. Markup to prepend to the image. Default empty.
115135
* @type string $after Optional. Markup to append to the image. Default empty.
136+
* @type boolean $is_lcp Optional. When true, applies LCP-friendly attributes.
116137
*
117138
* }
118139
*
@@ -121,3 +142,130 @@ function get_the_image( int $image_id, array $attributes, array $settings = [] )
121142
function the_image( int $image_id, array $attributes, array $settings = [] ): void {
122143
echo get_the_image( $image_id, $attributes, $settings );
123144
}
145+
146+
/**
147+
* Read intrinsic dimensions from a static file under the active theme directory.
148+
*
149+
* @usage BEA\Theme\Framework\Helpers\Formatting\Image\get_theme_static_image_dimensions( 'dist/images/logo.svg' );
150+
*
151+
* @param string $relative_theme_path Path relative to the theme root (e.g. dist/images/logo.svg).
152+
*
153+
* @return array{width:int,height:int}|null Null when the file is missing or dimensions cannot be read.
154+
*/
155+
function get_theme_static_image_dimensions( string $relative_theme_path ): ?array {
156+
$relative_theme_path = ltrim( $relative_theme_path, '/' );
157+
$file_path = get_theme_file_path( $relative_theme_path );
158+
159+
if ( ! is_string( $file_path ) || '' === $file_path || ! is_readable( $file_path ) ) {
160+
return null;
161+
}
162+
163+
if ( str_ends_with( strtolower( $file_path ), '.svg' ) ) {
164+
$contents = file_get_contents( $file_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local theme SVG asset.
165+
166+
if ( ! is_string( $contents ) || '' === $contents ) {
167+
return null;
168+
}
169+
170+
if ( preg_match( '/\bwidth="(\d+(?:\.\d+)?)"/', $contents, $width_match )
171+
&& preg_match( '/\bheight="(\d+(?:\.\d+)?)"/', $contents, $height_match ) ) {
172+
return [
173+
'width' => (int) round( (float) $width_match[1] ),
174+
'height' => (int) round( (float) $height_match[1] ),
175+
];
176+
}
177+
178+
if ( preg_match( '/\bviewBox="[\d.\s-]+?\s+([\d.]+)\s+([\d.]+)"/', $contents, $view_box_match ) ) {
179+
return [
180+
'width' => max( 1, (int) round( (float) $view_box_match[1] ) ),
181+
'height' => max( 1, (int) round( (float) $view_box_match[2] ) ),
182+
];
183+
}
184+
185+
return null;
186+
}
187+
188+
$size = wp_getimagesize( $file_path );
189+
if ( ! is_array( $size ) || empty( $size[0] ) || empty( $size[1] ) ) {
190+
return null;
191+
}
192+
193+
return [
194+
'width' => (int) $size[0],
195+
'height' => (int) $size[1],
196+
];
197+
}
198+
199+
/**
200+
* Build an img tag for a static theme asset, with width and height when known (prevents CLS).
201+
*
202+
* @usage BEA\Theme\Framework\Helpers\Formatting\Image\get_theme_static_image_markup( 'dist/images/logo.svg', [ 'alt' => 'Logo' ] );
203+
*
204+
* @param string $relative_theme_path Path relative to the theme root.
205+
* @param array $attributes Img attributes. src and alt are set when omitted.
206+
* An empty alt is output as alt="" (decorative image);
207+
* false or null omits the attribute.
208+
*
209+
* @return string Return the markup of the image
210+
*/
211+
function get_theme_static_image_markup( string $relative_theme_path, array $attributes = [] ): string {
212+
$relative_theme_path = ltrim( $relative_theme_path, '/' );
213+
214+
$attributes = wp_parse_args(
215+
$attributes,
216+
[
217+
'src' => get_theme_file_uri( $relative_theme_path ),
218+
'alt' => '',
219+
]
220+
);
221+
222+
$dimensions = get_theme_static_image_dimensions( $relative_theme_path );
223+
if ( null !== $dimensions ) {
224+
if ( ! isset( $attributes['width'] ) ) {
225+
$attributes['width'] = (string) $dimensions['width'];
226+
}
227+
if ( ! isset( $attributes['height'] ) ) {
228+
$attributes['height'] = (string) $dimensions['height'];
229+
}
230+
}
231+
232+
if ( isset( $attributes['fetchpriority'] ) && 'high' === $attributes['fetchpriority'] ) {
233+
$attributes['loading'] = false;
234+
}
235+
236+
$processor = new \WP_HTML_Tag_Processor( '<img>' );
237+
if ( ! $processor->next_tag( 'img' ) ) {
238+
return '';
239+
}
240+
241+
foreach ( $attributes as $name => $value ) {
242+
$name = (string) $name;
243+
244+
if ( false === $value || null === $value ) {
245+
$processor->remove_attribute( $name );
246+
continue;
247+
}
248+
249+
// Empty alt marks a decorative image; omitting the attribute is not equivalent for AT.
250+
if ( '' === $value && 'alt' !== $name ) {
251+
$processor->remove_attribute( $name );
252+
continue;
253+
}
254+
255+
$processor->set_attribute( $name, (string) $value );
256+
}
257+
258+
return $processor->get_updated_html();
259+
}
260+
261+
/**
262+
* @usage BEA\Theme\Framework\Helpers\Formatting\Image\the_theme_static_image( 'dist/images/logo.svg', [ 'alt' => 'Logo' ] );
263+
*
264+
* @param string $relative_theme_path Path relative to the theme root.
265+
* @param array $attributes Img attributes, see get_theme_static_image_markup().
266+
*
267+
* @return void Echo of the image markup
268+
*/
269+
function the_theme_static_image( string $relative_theme_path, array $attributes = [] ): void {
270+
echo get_theme_static_image_markup( $relative_theme_path, $attributes ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Attributes are escaped by WP_HTML_Tag_Processor.
271+
}

‎inc/Services/Performance.php‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ public function boot( Service_Container $container ): void {
2525
* Add hooks for the scripts and styles to hook on
2626
*/
2727
add_action( 'wp', [ $this, 'register_assets' ] );
28+
add_action( 'wp_head', [ $this, 'preload_fonts' ], 1 );
29+
add_filter( 'get_custom_logo_image_attributes', [ $this, 'deprioritize_custom_logo' ], 20 );
2830
}
2931

3032
/**
@@ -45,6 +47,66 @@ public function register_assets(): void {
4547
wp_add_inline_script( 'jquery', $this->passive_touchstart() );
4648
}
4749

50+
/**
51+
* Preload the woff2 fonts used by the above-the-fold content.
52+
*
53+
* Opt-in: the list is empty by default. Only preload fonts that are actually
54+
* rendered on first paint, otherwise they compete with the LCP resource.
55+
*
56+
* @usage add_filter( 'bea_theme_framework_preload_fonts', fn() => [ 'dist/fonts/my-font.woff2' ] );
57+
*
58+
* @return void
59+
*/
60+
public function preload_fonts(): void {
61+
if ( is_admin() ) {
62+
return;
63+
}
64+
65+
/**
66+
* Filter the font files to preload, relative to the theme root.
67+
*
68+
* @param string[] $fonts Font paths relative to the theme root. Default empty.
69+
*/
70+
$fonts = apply_filters( 'bea_theme_framework_preload_fonts', [] );
71+
if ( ! is_array( $fonts ) ) {
72+
return;
73+
}
74+
75+
foreach ( $fonts as $relative_path ) {
76+
if ( ! is_string( $relative_path ) || '' === $relative_path ) {
77+
continue;
78+
}
79+
80+
$relative_path = ltrim( $relative_path, '/' );
81+
$path = get_theme_file_path( $relative_path );
82+
if ( ! is_readable( $path ) ) {
83+
continue;
84+
}
85+
86+
printf(
87+
'<link rel="preload" href="%s" as="font" type="font/woff2" crossorigin>' . "\n",
88+
esc_url( get_theme_file_uri( $relative_path ) )
89+
);
90+
}
91+
}
92+
93+
/**
94+
* Prevent the site logo from competing with the real LCP candidate.
95+
*
96+
* @param array $custom_logo_attr Image attributes for the custom logo.
97+
*
98+
* @return array
99+
*/
100+
public function deprioritize_custom_logo( $custom_logo_attr ): array {
101+
if ( ! is_array( $custom_logo_attr ) ) {
102+
return [];
103+
}
104+
105+
$custom_logo_attr['fetchpriority'] = 'low';
106+
107+
return $custom_logo_attr;
108+
}
109+
48110
/**
49111
* Add passsive touchstart for performance
50112
* @return string

0 commit comments

Comments
 (0)