PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.4.0
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.4.0
1.4.1 1.4.0 1.3.7 1.3.6 1.3.5 1.3.4 1.3.3 1.3.2 1.3.1 1.3.0 1.2.4 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 All 35 releases
← All changes | includes/class-resource-hints-processor.php +572 -34 1.3.6 → 1.4.0 View file →
@@ -59,9 +59,9 @@
59 59
60 60 if ( ! empty( $opts['lcp_preload'] ) ) {
61 61 $count = max( 0, (int) ( $opts['lcp_image_count'] ?? 1 ) );
62 62 $exclusions = array_filter( array_map( 'strval', (array) ( $opts['lcp_exclusions'] ?? array() ) ) );
63 - [ $html, $preload ] = self::build_lcp_preload( $html, $count, $exclusions );
63 + [ $html, $preload ] = self::build_lcp_preload( $html, $count, $exclusions, (string) ( $opts['page_url'] ?? '' ) );
64 64 $hints .= $preload;
65 65 }
66 66
67 67 // The manual list runs AFTER the automatic pick so it can deduplicate
@@ -148,26 +148,37 @@
148 148 return $out;
149 149 }
150 150
151 151 /**
152 - * Strip core `loading="lazy"` and add `fetchpriority="high"` +
153 - * `decoding="async"` on every <img> whose tag matches one of the given
154 - * exclusion substrings. Mirrors what Lazy_Loader does for an excluded image
155 - * inside the_content, but page-wide so heroes outside it are covered too.
156 - * (FBS-83553 H2)
152 + * Strip core `loading="lazy"` and add `decoding="async"` on every <img>
153 + * whose tag matches one of the given exclusion substrings. Mirrors what
154 + * Lazy_Loader does for an excluded image inside the_content, but page-wide
155 + * so heroes outside it are covered too. (FBS-83553 H2)
157 156 *
157 + * Only the first visible match outside <footer>/<nav>/<aside> gets
158 + * `fetchpriority="high"`, and only when no image in the page holds it yet.
159 + * Every match used to get it, so a pattern naming the header and footer
160 + * logo, or a hero in a closed accordion, put several images at High. (#558)
161 + *
158 162 * @param string $html Full page HTML.
159 163 * @param string[] $exclusions Substring patterns identifying above-the-fold heroes.
160 164 */
161 165 private static function promote_excluded_images( string $html, array $exclusions ): string {
162 - return (string) preg_replace_callback(
163 - '#<img\b(?:"[^"]*"|\'[^\']*\'|[^>"\'])*>#i',
164 - static function ( array $m ) use ( $exclusions ) {
165 - $tag = $m[0];
166 + $img_re = '#<img\b(?:"[^"]*"|\'[^\']*\'|[^>"\'])*>#i';
167 + $claimed = (bool) preg_match( '#<img\b(?:"[^"]*"|\'[^\']*\'|[^>"\'])*?(?<![-\w])fetchpriority\s*=\s*["\']?high\b#i', $html );
168 + $skip = $claimed ? array() : array_merge( self::chrome_container_ranges( $html ), Lazy_Loader::hidden_ranges( $html ) );
169 +
170 + $result = preg_replace_callback(
171 + $img_re,
172 + static function ( array $m ) use ( $exclusions, &$claimed, $skip ) {
173 + [ $tag, $offset ] = $m[0];
166 174 foreach ( $exclusions as $needle ) {
167 175 if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
168 176 $tag = (string) preg_replace( '#\s*\bloading=(["\'])\s*lazy\s*\1#i', '', $tag );
169 - $tag = self::set_fetchpriority( $tag );
177 + if ( ! $claimed && ! self::offset_in_ranges( (int) $offset, $skip ) && ! Lazy_Loader::tag_is_hidden( $tag, 'img' ) ) {
178 + $tag = self::set_fetchpriority( $tag );
179 + $claimed = true;
180 + }
170 181 if ( ! preg_match( '#\bdecoding=#i', $tag ) ) {
171 182 $tag = (string) preg_replace( '#<img\b#i', '<img decoding="async"', $tag, 1 );
172 183 }
173 184 return $tag;
@@ -174,10 +185,15 @@
174 185 }
175 186 }
176 187 return $tag;
177 188 },
178 - $html
189 + $html,
190 + -1,
191 + $count,
192 + PREG_OFFSET_CAPTURE
179 193 );
194 +
195 + return is_string( $result ) ? $result : $html;
180 196 }
181 197
182 198 /**
183 199 * Build preconnect <link>s for detected font hosts + user hosts.
@@ -231,15 +247,57 @@
231 247 *
232 248 * @param string $html Page HTML.
233 249 * @param int $count How many top images to preload.
234 250 * @param string[] $exclusions Substring patterns that exempt an <img>.
251 + * @param string $page_url The page being served, for the candidate seam.
235 252 * @return array{0:string,1:string} [rewritten html, preload markup]
236 253 */
237 - private static function build_lcp_preload( string $html, int $count, array $exclusions ): array {
254 + private static function build_lcp_preload( string $html, int $count, array $exclusions, string $page_url = '' ): array {
238 255 if ( $count < 1 ) {
239 256 return array( $html, '' );
240 257 }
241 258
259 + /**
260 + * Supply the LCP preload candidate for this page instead of the
261 + * automatic pick.
262 + *
263 + * The automatic pick reads the served HTML, so it cannot see a hero set
264 + * as a background in an external stylesheet, and it skips an <img> that
265 + * WordPress core marked lazy. An extension that has measured the page in
266 + * a browser can answer instead. Return null to leave the automatic pick
267 + * in charge; return an array to replace it:
268 + *
269 + * - `url` (string) the image to preload; an empty string means the
270 + * page has no LCP image, so nothing is preloaded;
271 + * - `srcset` (string, optional) and `sizes` (string, optional), emitted
272 + * as `imagesrcset` / `imagesizes`;
273 + * - `kind` (string, optional) `img` or `background`, passed to the URL
274 + * filters below. An image no <img> on the page carries is a
275 + * background regardless;
276 + * - `media` (string, optional) a media query for the preload link.
277 + *
278 + * Or a list of up to three such arrays, each with its own `media`, when
279 + * phones and desktops paint different images: each device then preloads
280 + * its own. Any `media` (also on a single answer) sets the matched <img>s
281 + * to `loading="lazy"`, so a device never downloads the other one's hero.
282 + *
283 + * Anything else (an empty list, a URL that is not a string, a URL
284 + * esc_url() refuses, a relative URL such as `hero.png`, a `media` that
285 + * is not a string, over 200 characters or holding `<`, `>` or `"`) is
286 + * not understood, and the automatic pick runs.
287 + *
288 + * The `<img>` carrying that URL, if the page has one, gets
289 + * `fetchpriority="high"` and loses `loading="lazy"`. The URL filters
290 + * below (`xspeed_lcp_preload_url` and friends) still apply.
291 + *
292 + * @param array|null $candidate Null = no opinion.
293 + * @param string $page_url The page being served; empty outside a request.
294 + */
295 + $supplied = self::supplied_candidates( apply_filters( 'xspeed_lcp_preload_candidate', null, $page_url ) );
296 + if ( null !== $supplied ) {
297 + return self::build_supplied_preload( $html, $supplied );
298 + }
299 +
242 300 $preload = '';
243 301
244 302 // Snapshot of already-present preload markup, for idempotency: a second
245 303 // pass (e.g. cache-off ob_start over an already-processed body) must not
@@ -256,22 +314,21 @@
256 314 // one that matters, and the feature reported success either way. The
257 315 // marker list and size gate were heuristics layered on top of the
258 316 // wrong primitive rather than replacing it. (#96)
259 317 $candidates = array();
260 - $skip_ranges = self::chrome_container_ranges( $html );
318 + // Markup hidden on arrival (a closed <details>, `hidden`, inline
319 + // display:none) cannot paint as LCP either. Preloading the hero of a
320 + // closed accordion spent the page's one High fetch on it. (#558)
321 + $skip_ranges = array_merge( self::chrome_container_ranges( $html ), Lazy_Loader::hidden_ranges( $html ) );
322 + // <img> indexes that can't be the LCP however they are marked: chrome,
323 + // hidden, or a logo/icon. Only these give up a stray `high`. (#558)
324 + $ruled_out = array();
261 325 if ( preg_match_all( '#<img\b[^>]*>#i', $html, $matches, PREG_OFFSET_CAPTURE ) ) {
262 326 foreach ( $matches[0] as $index => $match ) {
263 327 [ $tag, $offset ] = $match;
264 328
265 329 // Skip anything the user excluded.
266 - $excluded = false;
267 - foreach ( $exclusions as $needle ) {
268 - if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
269 - $excluded = true;
270 - break;
271 - }
272 - }
273 - if ( $excluded ) {
330 + if ( self::matches_any( $tag, $exclusions ) ) {
274 331 continue;
275 332 }
276 333
277 334 // An image inside <footer>/<nav>/<aside> is site chrome by
@@ -278,9 +335,10 @@
278 335 // construction — a footer brand strip or FAQ illustration can
279 336 // never be the LCP element, whatever size it declares. On the
280 337 // FBS-84576 repro these decoys outranked the real hero three
281 338 // times on one layout.
282 - if ( self::offset_in_ranges( $offset, $skip_ranges ) ) {
339 + if ( self::offset_in_ranges( $offset, $skip_ranges ) || Lazy_Loader::tag_is_hidden( $tag, 'img' ) ) {
340 + $ruled_out[ $index ] = true;
283 341 continue;
284 342 }
285 343
286 344 // An image the theme explicitly lazy-loads is never the
@@ -302,8 +360,9 @@
302 360
303 361 // Chrome markers / explicit opt-out / obviously-tiny images
304 362 // never compete. (FBS-83553 H1 "logo before hero".)
305 363 if ( self::looks_too_small( $tag ) ) {
364 + $ruled_out[ $index ] = true;
306 365 continue;
307 366 }
308 367
309 368 $candidates[] = array(
@@ -312,8 +371,9 @@
312 371 'srcset' => $srcset,
313 372 'sizes' => $sizes,
314 373 'score' => self::weighted_score( self::lcp_score( $tag, $srcset ), $tag, $index ),
315 374 'order' => $index,
375 + 'offset' => $offset,
316 376 );
317 377 }
318 378 }
319 379
@@ -346,9 +406,29 @@
346 406 foreach ( self::style_block_candidates( $html, $exclusions, $skip_ranges ) as $sb ) {
347 407 $candidates[] = $sb;
348 408 }
349 409
410 + // A background video with no poster, ahead of every candidate, is the
411 + // hero. Nothing in its box is preloadable, and every image after it
412 + // sits lower on the page. Preloading the first of those spent the one
413 + // high-priority fetch on an image below the fold, ahead of the CSS.
414 + // Those images also give up a stray `high` from the lazy pass.
415 + $video_at = self::background_video_offset( $html, $skip_ranges );
416 + if ( null !== $video_at ) {
417 + foreach ( $candidates as $i => $c ) {
418 + if ( $c['offset'] > $video_at ) {
419 + if ( empty( $c['background'] ) ) {
420 + $ruled_out[ $c['order'] ] = true;
421 + }
422 + unset( $candidates[ $i ] );
423 + }
424 + }
425 + }
426 +
350 427 if ( empty( $candidates ) ) {
428 + if ( null !== $video_at ) {
429 + $html = self::demote_images( $html, $ruled_out );
430 + }
351 431 return array( $html, '' );
352 432 }
353 433
354 434 // Rank by score, biggest first. Document order breaks ties, so two
@@ -377,9 +457,9 @@
377 457 '#rel=["\']preload["\'][^>]*as=["\']image["\'][^>]*' . preg_quote( $w['src'], '#' ) . '#i',
378 458 $existing
379 459 );
380 460 if ( ! $already ) {
381 - $preload .= self::preload_link( $w['src'], $w['srcset'], $w['sizes'] );
461 + $preload .= self::preload_link( $w['src'], $w['srcset'], $w['sizes'], empty( $w['background'] ) ? 'img' : 'background' );
382 462 }
383 463 // Only <img> winners are promoted in PASS 2 — there is no
384 464 // fetchpriority/loading attribute to fix on a background element,
385 465 // and its `order` is offset past every <img> index precisely so it
@@ -392,14 +472,26 @@
392 472 // Rewrite only the winning tags. Counting occurrences rather than
393 473 // matching on tag text, because the same markup can legitimately
394 474 // appear more than once on a page and only the ranked instance should
395 475 // be promoted.
396 - $seen = -1;
397 - $html = preg_replace_callback(
476 + //
477 + // When an <img> wins, it is the page's one High image, so an image
478 + // that can't be the LCP (a logo, an icon, a hidden panel, chrome)
479 + // gives up any `high` it carries. That is usually the lazy pass handing
480 + // its slot to the first image in the_content. An image that merely scored
481 + // lower, or that the user kept out of the pick, keeps its hint: the
482 + // ranking can be wrong, and core or the theme may have named the real
483 + // hero. (#558)
484 + $demote = ! empty( $chosen ) || null !== $video_at ? $ruled_out : array();
485 + $seen = -1;
486 + $html = preg_replace_callback(
398 487 '#<img\b[^>]*>#i',
399 - static function ( array $m ) use ( &$seen, $chosen ) {
488 + static function ( array $m ) use ( &$seen, $chosen, $demote ) {
400 489 ++$seen;
401 490 if ( ! isset( $chosen[ $seen ] ) ) {
491 + if ( isset( $demote[ $seen ] ) && 'high' === strtolower( self::attr( $m[0], 'fetchpriority' ) ) ) {
492 + return (string) preg_replace( '#\s*(?<![-\w])fetchpriority\s*=\s*(["\']?)high\1#i', '', $m[0], 1 );
493 + }
402 494 return $m[0];
403 495 }
404 496 // Add fetchpriority="high" AND remove any loading="lazy" the
405 497 // theme / WP core left on the LCP image. fetchpriority="high"
@@ -414,8 +506,56 @@
414 506 return array( (string) $html, $preload );
415 507 }
416 508
417 509 /**
510 + * Byte offset of the first visible background video with no poster, or
511 + * null when the page has none.
512 + *
513 + * @param string $html Full page HTML.
514 + * @param array<int,array{0:int,1:int}> $skip_ranges Chrome and hidden spans.
515 + */
516 + private static function background_video_offset( string $html, array $skip_ranges ): ?int {
517 + $body = stripos( $html, '<body' );
518 + if ( ! preg_match_all( '#<video\b[^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE, false === $body ? 0 : $body ) ) {
519 + return null;
520 + }
521 + foreach ( $m[0] as [ $tag, $offset ] ) {
522 + if ( self::offset_in_ranges( $offset, $skip_ranges ) || Lazy_Loader::tag_is_hidden( $tag, 'video' ) ) {
523 + continue;
524 + }
525 + if ( Lazy_Loader::is_background_video_without_poster( $tag ) ) {
526 + return $offset;
527 + }
528 + }
529 + return null;
530 + }
531 +
532 + /**
533 + * Strip fetchpriority="high" from the <img> tags at the given indexes.
534 + *
535 + * @param string $html Page HTML.
536 + * @param array<int,bool> $indexes <img> indexes, in document order.
537 + */
538 + private static function demote_images( string $html, array $indexes ): string {
539 + if ( empty( $indexes ) ) {
540 + return $html;
541 + }
542 + $seen = -1;
543 + $out = preg_replace_callback(
544 + '#<img\b[^>]*>#i',
545 + static function ( array $m ) use ( &$seen, $indexes ) {
546 + ++$seen;
547 + if ( isset( $indexes[ $seen ] ) && 'high' === strtolower( self::attr( $m[0], 'fetchpriority' ) ) ) {
548 + return (string) preg_replace( '#\s*(?<![-\w])fetchpriority\s*=\s*(["\']?)high\1#i', '', $m[0], 1 );
549 + }
550 + return $m[0];
551 + },
552 + $html
553 + );
554 + return null === $out ? $html : $out;
555 + }
556 +
557 + /**
418 558 * Collect CSS `background-image` heroes as LCP candidates.
419 559 *
420 560 * Only INLINE `style` attributes are read. A background declared in an
421 561 * external stylesheet is invisible here by design: resolving it would mean
@@ -487,8 +627,9 @@
487 627 'score' => (float) $area,
488 628 // Offset so a background never ties ahead of an <img> that
489 629 // appeared earlier in the document; ties still break on order.
490 630 'order' => 100000 + $index,
631 + 'offset' => $offset,
491 632 'background' => true,
492 633 );
493 634 }
494 635
@@ -544,8 +685,9 @@
544 685 'srcset' => '',
545 686 'sizes' => '',
546 687 'score' => (float) $area,
547 688 'order' => 100000 + $index,
689 + 'offset' => $offset,
548 690 'background' => true,
549 691 );
550 692 }
551 693
@@ -648,8 +790,9 @@
648 790 // Offset past the inline-style backgrounds: a rule-matched
649 791 // background is one inference step less certain, so it must
650 792 // never tie ahead of one read straight off the element.
651 793 'order' => 200000 + $offset,
794 + 'offset' => $offset,
652 795 'background' => true,
653 796 );
654 797 }
655 798 }
@@ -926,12 +1069,29 @@
926 1069 }
927 1070 return $ranges;
928 1071 }
929 1072
1073 + /**
1074 + * Does a tag contain any of the given substring patterns?
1075 + *
1076 + * @param string[] $patterns
1077 + */
1078 + private static function matches_any( string $tag, array $patterns ): bool {
1079 + foreach ( $patterns as $needle ) {
1080 + if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
1081 + return true;
1082 + }
1083 + }
1084 + return false;
1085 + }
1086 +
930 1087 /** Does a byte offset fall inside any of the given [start, end] ranges? */
931 1088 private static function offset_in_ranges( int $offset, array $ranges ): bool {
932 1089 foreach ( $ranges as $range ) {
933 - if ( $offset > $range[0] && $offset < $range[1] ) {
1090 + // >= on the start: a closed <details> span from
1091 + // Lazy_Loader::hidden_ranges() opens right at the first image
1092 + // after its <summary>.
1093 + if ( $offset >= $range[0] && $offset < $range[1] ) {
934 1094 return true;
935 1095 }
936 1096 }
937 1097 return false;
@@ -988,9 +1148,9 @@
988 1148 * resource goes un-preloaded). By filtering the URL, a webp/avif layer can
989 1149 * redirect the preload to the format it will actually serve, WITHOUT Free
990 1150 * knowing that layer exists. (FBS-83553 H3)
991 1151 */
992 - private static function preload_link( string $src, string $srcset, string $sizes ): string {
1152 + private static function preload_link( string $src, string $srcset, string $sizes, string $kind = 'img', string $media = '' ): string {
993 1153 // Resolve the `type` from the ORIGINAL image URL (before rewriting), so a
994 1154 // negotiating layer can key off the source .jpg/.png — after rewriting,
995 1155 // the URL is already a .webp and the derivation would no-op.
996 1156 $original = $src;
@@ -1001,20 +1161,28 @@
1001 1161 * even though the markup is baked into a shared cache file.
1002 1162 *
1003 1163 * @param string $type Defaults to '' (no type attribute).
1004 1164 * @param string $src The ORIGINAL (pre-rewrite) preload URL.
1165 + * @param string $kind `img` for an <img>, `background` for a CSS
1166 + * background or a video poster. Only an <img> can be
1167 + * wrapped in <picture>; a background is requested by
1168 + * the URL its stylesheet names.
1005 1169 */
1006 - $type = (string) apply_filters( 'xspeed_lcp_preload_type', '', $original );
1170 + $type = (string) apply_filters( 'xspeed_lcp_preload_type', '', $original, $kind );
1007 1171 /**
1008 1172 * Filter the LCP preload href. Return a modern-format sibling (webp/avif)
1009 1173 * when one will actually be served for this image.
1010 1174 *
1011 - * @param string $src The original image URL chosen for preload.
1175 + * @param string $src The original image URL chosen for preload.
1176 + * @param string $kind `img` or `background`, as for xspeed_lcp_preload_type.
1012 1177 */
1013 - $src = (string) apply_filters( 'xspeed_lcp_preload_url', $src );
1178 + $src = (string) apply_filters( 'xspeed_lcp_preload_url', $src, $kind );
1014 1179 if ( '' !== $srcset ) {
1015 - /** @param string $srcset The original srcset chosen for preload. */
1016 - $srcset = (string) apply_filters( 'xspeed_lcp_preload_srcset', $srcset );
1180 + /**
1181 + * @param string $srcset The original srcset chosen for preload.
1182 + * @param string $kind `img` or `background`.
1183 + */
1184 + $srcset = (string) apply_filters( 'xspeed_lcp_preload_srcset', $srcset, $kind );
1017 1185 }
1018 1186
1019 1187 $attrs = sprintf( 'href="%s"', esc_url( $src ) );
1020 1188
@@ -1030,8 +1198,12 @@
1030 1198 if ( '' !== $type ) {
1031 1199 $attrs .= sprintf( ' type="%s"', esc_attr( $type ) );
1032 1200 }
1033 1201
1202 + if ( '' !== $media ) {
1203 + $attrs .= sprintf( ' media="%s"', esc_attr( $media ) );
1204 + }
1205 +
1034 1206 return sprintf( '<link rel="preload" as="image" %s fetchpriority="high">' . "\n", $attrs );
1035 1207 }
1036 1208
1037 1209 /**
@@ -1136,9 +1308,226 @@
1136 1308 }
1137 1309 return (int) $w <= self::MIN_LCP_DIMENSION && (int) $h <= self::MIN_LCP_DIMENSION;
1138 1310 }
1139 1311
1312 + /** Most candidates one answer may carry (one per device class). */
1313 + private const MAX_SUPPLIED_CANDIDATES = 3;
1314 +
1140 1315 /**
1316 + * The filter's answer as a list of well-formed candidates, or null when
1317 + * it is no answer or not one this understands (then the automatic pick
1318 + * runs). An empty list means "this page has no LCP image".
1319 + *
1320 + * @param mixed $answer What `xspeed_lcp_preload_candidate` returned.
1321 + * @return array<int,array{url:string,srcset:string,sizes:string,kind:string,media:string}>|null
1322 + */
1323 + private static function supplied_candidates( $answer ): ?array {
1324 + if ( ! is_array( $answer ) || empty( $answer ) ) {
1325 + return null;
1326 + }
1327 + $items = array_key_exists( 'url', $answer ) ? array( $answer ) : $answer;
1328 + if ( array_values( $items ) !== $items || count( $items ) > self::MAX_SUPPLIED_CANDIDATES ) {
1329 + return null;
1330 + }
1331 + $out = array();
1332 + foreach ( $items as $item ) {
1333 + if ( ! is_array( $item ) || ! array_key_exists( 'url', $item ) || ! is_string( $item['url'] ) ) {
1334 + return null;
1335 + }
1336 + $url = trim( $item['url'] );
1337 + if ( '' === $url ) {
1338 + // "No LCP image" only makes sense as the whole answer.
1339 + if ( 1 === count( $items ) ) {
1340 + return array();
1341 + }
1342 + return null;
1343 + }
1344 + // Absolute, protocol-relative or root-relative. A bare `hero.png`
1345 + // passed esc_url() as `http://hero.png`: a high-priority fetch to
1346 + // a host that does not exist.
1347 + if ( '' === esc_url( $url ) || ! preg_match( '#^(?:https?:)?/#i', $url ) ) {
1348 + return null;
1349 + }
1350 + // A media rule this cannot use rejects the answer. Dropping only
1351 + // the rule kept the preload and sent it to every device.
1352 + $media = $item['media'] ?? '';
1353 + if ( ! is_string( $media ) || strlen( $media ) > 200 || preg_match( '#[<>"]#', $media ) ) {
1354 + return null;
1355 + }
1356 + $text = static fn ( $v, int $max ): string => ( is_string( $v ) && strlen( $v ) <= $max ) ? trim( $v ) : '';
1357 + $out[] = array(
1358 + 'url' => $url,
1359 + 'srcset' => $text( $item['srcset'] ?? '', 4096 ),
1360 + 'sizes' => $text( $item['sizes'] ?? '', 512 ),
1361 + 'kind' => 'background' === ( $item['kind'] ?? '' ) ? 'background' : 'img',
1362 + 'media' => trim( $media ),
1363 + );
1364 + }
1365 + return $out;
1366 + }
1367 +
1368 + /**
1369 + * Preload what an extension supplied, and promote the <img> it names.
1370 + *
1371 + * The answer is measured, not guessed, so every other <img> gives up a
1372 + * stray `fetchpriority="high"`: two High images compete with the one
1373 + * that paints first.
1374 + *
1375 + * @param string $html Page HTML.
1376 + * @param array<int,array{url:string,srcset:string,sizes:string,kind:string,media:string}> $candidates From supplied_candidates().
1377 + * @return array{0:string,1:string} [rewritten html, preload markup]
1378 + */
1379 + private static function build_supplied_preload( string $html, array $candidates ): array {
1380 + // Scoped when any preload carries a media rule, even a single one:
1381 + // Pro sends one desktop-only candidate when the phone's LCP is text,
1382 + // and promoting that <img> made phones download a hero they hide.
1383 + $scoped = '' !== implode( '', array_column( $candidates, 'media' ) );
1384 + $skip = array_merge( self::chrome_container_ranges( $html ), Lazy_Loader::hidden_ranges( $html ) );
1385 +
1386 + // Which <img> index each candidate promotes: the first one, outside
1387 + // site chrome and hidden markup, whose src or one of whose srcset
1388 + // URLs IS the candidate. A substring match picked an earlier image
1389 + // whose srcset merely contained the name.
1390 + // Two candidates may claim the same <img>: a phone and a desktop size
1391 + // of one responsive image. The second one is still an <img>, not a
1392 + // background.
1393 + $promote = array();
1394 + $matched = array();
1395 + if ( preg_match_all( '#<img\b[^>]*>#i', $html, $imgs, PREG_OFFSET_CAPTURE ) ) {
1396 + foreach ( $candidates as $c => $candidate ) {
1397 + foreach ( $imgs[0] as $index => $match ) {
1398 + [ $tag, $offset ] = $match;
1399 + if ( self::offset_in_ranges( $offset, $skip ) || Lazy_Loader::tag_is_hidden( $tag, 'img' ) ) {
1400 + continue;
1401 + }
1402 + [ $src, $img_srcset, $img_sizes ] = self::effective_image_src( $tag );
1403 + if ( ! self::same_url( $src, $candidate['url'] ) && ! self::srcset_has( $img_srcset, $candidate['url'] ) ) {
1404 + continue;
1405 + }
1406 + $promote[ $index ] = true;
1407 + $matched[ $c ] = true;
1408 + // The <img> may already be served as a format sibling the
1409 + // answer did not name (`hero.png.webp` for `hero.png`: an
1410 + // image plugin swapped it for this browser). Preload what
1411 + // the <img> will fetch, or the page downloads both.
1412 + if ( self::format_original( $src ) !== $src ) {
1413 + $candidates[ $c ]['url'] = html_entity_decode( $src, ENT_QUOTES );
1414 + $candidates[ $c ]['srcset'] = html_entity_decode( $img_srcset, ENT_QUOTES );
1415 + $candidates[ $c ]['sizes'] = $img_sizes;
1416 + }
1417 + // An answer that names only the URL still gets the <img>'s
1418 + // responsive set: without it the preload fetches the full
1419 + // file and the browser then downloads the size it shows.
1420 + if ( '' === $candidates[ $c ]['srcset'] && '' !== $img_srcset ) {
1421 + $candidates[ $c ]['srcset'] = $img_srcset;
1422 + $candidates[ $c ]['sizes'] = $img_sizes;
1423 + }
1424 + break;
1425 + }
1426 + }
1427 + }
1428 +
1429 + $seen = -1;
1430 + $html = (string) preg_replace_callback(
1431 + '#<img\b[^>]*>#i',
1432 + static function ( array $m ) use ( &$seen, $promote, $scoped ) {
1433 + ++$seen;
1434 + if ( isset( $promote[ $seen ] ) ) {
1435 + // Scoped to a device: make the <img> lazy, so the device
1436 + // that hides it never downloads it. Keeping whatever
1437 + // `loading` it had was not enough: Lazy Load's default
1438 + // "load the first image straight away" had already made
1439 + // it eager. The device that shows it gets it from its own
1440 + // preload, which already fetched it early.
1441 + return $scoped ? self::force_lazy( self::set_fetchpriority( $m[0] ) ) : self::promote_lcp_img( $m[0] );
1442 + }
1443 + if ( 'high' === strtolower( self::attr( $m[0], 'fetchpriority' ) ) ) {
1444 + return (string) preg_replace( '#\s*(?<![-\w])fetchpriority\s*=\s*(["\']?)high\1#i', '', $m[0], 1 );
1445 + }
1446 + return $m[0];
1447 + },
1448 + $html
1449 + );
1450 +
1451 + $preload = '';
1452 + foreach ( $candidates as $c => $candidate ) {
1453 + // Idempotency, as for the automatic pick: a second pass over an
1454 + // already-processed body must not emit the link twice. Compared
1455 + // with `&amp;` decoded, the way the markup spells a query.
1456 + $already = false;
1457 + if ( preg_match_all( '#<link\b[^>]*rel=["\']preload["\'][^>]*>#i', $html, $links ) ) {
1458 + foreach ( $links[0] as $link ) {
1459 + if ( false !== strpos( html_entity_decode( $link, ENT_QUOTES ), $candidate['url'] ) ) {
1460 + $already = true;
1461 + break;
1462 + }
1463 + }
1464 + }
1465 + if ( $already ) {
1466 + continue;
1467 + }
1468 + // An image the page shows through no <img> is a background,
1469 + // whatever the answer said: nothing here can wrap it in <picture>.
1470 + $kind = isset( $matched[ $c ] ) ? $candidate['kind'] : 'background';
1471 + $preload .= self::preload_link( $candidate['url'], $candidate['srcset'], $candidate['sizes'], $kind, $candidate['media'] );
1472 + }
1473 + return array( $html, $preload );
1474 + }
1475 +
1476 + /** Set `loading="lazy"` on an <img>, replacing any other loading value. */
1477 + private static function force_lazy( string $tag ): string {
1478 + $tag = (string) preg_replace( '#\s*(?<![-\w])loading\s*=\s*(["\']?)[a-z]*\1#i', '', $tag, 1 );
1479 + return (string) preg_replace( '#<img\b#i', '<img loading="lazy"', $tag, 1 );
1480 + }
1481 +
1482 + /** Two URLs name the same image: `&amp;` decoded, and a root-relative one compared by path. */
1483 + private static function same_url( string $a, string $b ): bool {
1484 + $a = html_entity_decode( $a, ENT_QUOTES );
1485 + $b = html_entity_decode( $b, ENT_QUOTES );
1486 + if ( '' === $a || '' === $b ) {
1487 + return false;
1488 + }
1489 + if ( $a === $b ) {
1490 + return true;
1491 + }
1492 + // A format sibling is the same image: `hero.png.webp` is `hero.png`.
1493 + $a = self::format_original( $a );
1494 + $b = self::format_original( $b );
1495 + if ( $a === $b ) {
1496 + return true;
1497 + }
1498 + $rel = static function ( string $u ): string {
1499 + if ( 0 === strpos( $u, '/' ) && 0 !== strpos( $u, '//' ) ) {
1500 + return $u;
1501 + }
1502 + $path = (string) wp_parse_url( $u, PHP_URL_PATH );
1503 + $query = (string) wp_parse_url( $u, PHP_URL_QUERY );
1504 + return $path . ( '' !== $query ? '?' . $query : '' );
1505 + };
1506 + return ( 0 === strpos( $a, '/' ) || 0 === strpos( $b, '/' ) ) && $rel( $a ) === $rel( $b );
1507 + }
1508 +
1509 + /**
1510 + * The original of a modern-format sibling that appends its extension,
1511 + * `hero.png.webp` → `hero.png`, the naming ShortPixel, Imagify and other
1512 + * image plugins use. Any other URL comes back unchanged.
1513 + */
1514 + private static function format_original( string $url ): string {
1515 + return (string) preg_replace( '#(\.(?:jpe?g|png))\.(?:webp|avif)(?=$|\?)#i', '$1', $url );
1516 + }
1517 +
1518 + /** Whether one of the URLs in a srcset IS $url (not merely contains it). */
1519 + private static function srcset_has( string $srcset, string $url ): bool {
1520 + foreach ( explode( ',', $srcset ) as $entry ) {
1521 + $candidate = strtok( trim( $entry ), " \t\n" );
1522 + if ( false !== $candidate && self::same_url( $candidate, $url ) ) {
1523 + return true;
1524 + }
1525 + }
1526 + return false;
1527 + }
1528 +
1529 + /**
1141 1530 * Promote an <img> to the LCP element: force fetchpriority="high" and
1142 1531 * strip any loading="lazy" so the browser loads it immediately. Both are
1143 1532 * idempotent. `loading="lazy"` is REMOVED rather than flipped to "eager"
1144 1533 * because eager is the default; a bare tag with fetchpriority="high" is
@@ -1169,8 +1558,16 @@
1169 1558 * before the first stylesheet so the preloads are discovered before the
1170 1559 * render-blocking CSS. Falls back to after <head>, then prepend.
1171 1560 */
1172 1561 private static function inject_into_head( string $html, string $hints ): string {
1562 + // Only a supplied candidate's preload carries `media`. Every other
1563 + // page keeps exactly the placement it had before the seam existed.
1564 + if ( false !== strpos( $hints, ' media="' ) ) {
1565 + $pos = self::after_viewport_offset( $html );
1566 + if ( null !== $pos ) {
1567 + return substr( $html, 0, $pos ) . "\n" . $hints . substr( $html, $pos );
1568 + }
1569 + }
1173 1570 // Before the first <link rel="stylesheet"> if there is one.
1174 1571 if ( preg_match( '#<link\b[^>]*rel=["\']stylesheet["\'][^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE ) ) {
1175 1572 $pos = $m[0][1];
1176 1573 return substr( $html, 0, $pos ) . $hints . substr( $html, $pos );
@@ -1181,6 +1578,147 @@
1181 1578 return substr( $html, 0, $pos ) . "\n" . $hints . substr( $html, $pos );
1182 1579 }
1183 1580 // No head at all — prepend (degenerate documents).
1184 1581 return $hints . $html;
1582 + }
1583 +
1584 + /**
1585 + * Where a media-scoped preload goes: before the first stylesheet, as
1586 + * usual, but never ahead of <meta name="viewport">. Null when the head
1587 + * could not be read, and the usual placement is used instead.
1588 + *
1589 + * A preload's `media` is evaluated when the parser reaches the link, and
1590 + * until the viewport meta is parsed a phone lays out at its default
1591 + * desktop width. A `(min-width: 768px)` preload placed earlier matched on
1592 + * phones too and fetched the desktop hero at high priority.
1593 + *
1594 + * Reads only the head, tag by tag, so a viewport meta or a stylesheet
1595 + * written inside a script string, a comment or an attribute value is
1596 + * never taken for a real one. That put the hints inside a script, which
1597 + * then threw a SyntaxError. A pattern over the whole page did the same
1598 + * job but could give up on a large inline block, and then searched the
1599 + * raw markup.
1600 + *
1601 + * @return int|null Byte offset in $html.
1602 + */
1603 + private static function after_viewport_offset( string $html ) {
1604 + $len = strlen( $html );
1605 + $i = 0;
1606 + $head_start = null;
1607 + $stylesheet = null;
1608 + $viewport = null;
1609 + while ( $i < $len ) {
1610 + $lt = strpos( $html, '<', $i );
1611 + if ( false === $lt ) {
1612 + break;
1613 + }
1614 + if ( 0 === substr_compare( $html, '<!--', $lt, 4 ) ) {
1615 + // `<!-->` and `<!--->` close at once, so look from the second dash.
1616 + $close = strpos( $html, '-->', $lt + 2 );
1617 + if ( false === $close ) {
1618 + return null;
1619 + }
1620 + $i = $close + 3;
1621 + continue;
1622 + }
1623 + if ( ! preg_match( '#\G<(/?)([a-z][a-z0-9-]*)#i', $html, $t, 0, $lt ) ) {
1624 + $i = $lt + 1;
1625 + continue;
1626 + }
1627 + $gt = self::tag_end( $html, $lt + strlen( $t[0] ) );
1628 + if ( null === $gt ) {
1629 + return null;
1630 + }
1631 + $name = strtolower( $t[2] );
1632 + $tag = substr( $html, $lt, $gt + 1 - $lt );
1633 + $i = $gt + 1;
1634 +
1635 + if ( '/' === $t[1] ) {
1636 + if ( 'head' === $name ) {
1637 + break;
1638 + }
1639 + continue;
1640 + }
1641 + if ( 'head' === $name ) {
1642 + $head_start = $i;
1643 + continue;
1644 + }
1645 + if ( 'body' === $name ) {
1646 + break;
1647 + }
1648 + if ( in_array( $name, array( 'script', 'style', 'noscript', 'template', 'title', 'textarea' ), true ) ) {
1649 + $close = stripos( $html, '</' . $name, $i );
1650 + if ( false === $close ) {
1651 + return null;
1652 + }
1653 + $i = $close;
1654 + continue;
1655 + }
1656 + if ( null === $head_start ) {
1657 + continue;
1658 + }
1659 + if ( 'link' !== $name && 'meta' !== $name ) {
1660 + continue;
1661 + }
1662 + $attrs = self::tag_attrs( $tag );
1663 + if ( null === $stylesheet && 'link' === $name && 'stylesheet' === strtolower( $attrs['rel'] ?? '' ) ) {
1664 + if ( null !== $viewport ) {
1665 + return $lt;
1666 + }
1667 + $stylesheet = $lt;
1668 + continue;
1669 + }
1670 + if ( null === $viewport && 'meta' === $name && 'viewport' === strtolower( $attrs['name'] ?? '' ) ) {
1671 + if ( null !== $stylesheet ) {
1672 + return $i;
1673 + }
1674 + $viewport = $i;
1675 + }
1676 + }
1677 + if ( null !== $stylesheet ) {
1678 + return $stylesheet;
1679 + }
1680 + return $viewport ?? $head_start;
1681 + }
1682 +
1683 + /**
1684 + * A tag's attributes, read in order so a quoted value is consumed whole:
1685 + * `content="name=viewport"` is a content attribute, not a name.
1686 + *
1687 + * @return array<string,string> Lowercase name => trimmed value; the first of a repeated name wins.
1688 + */
1689 + private static function tag_attrs( string $tag ): array {
1690 + $out = array();
1691 + preg_match_all( '#\s([^\s=/>"\']+)(?:\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+))?#', $tag, $m, PREG_SET_ORDER );
1692 + foreach ( $m as $a ) {
1693 + $key = strtolower( $a[1] );
1694 + if ( ! isset( $out[ $key ] ) ) {
1695 + $out[ $key ] = trim( trim( $a[2] ?? '', '"\'' ) );
1696 + }
1697 + }
1698 + return $out;
1699 + }
1700 +
1701 + /**
1702 + * Offset of the `>` that ends a tag whose attributes start at $from,
1703 + * stepping over quoted values so `content="a>b"` does not end it early.
1704 + *
1705 + * @return int|null
1706 + */
1707 + private static function tag_end( string $html, int $from ) {
1708 + $len = strlen( $html );
1709 + $quote = '';
1710 + for ( $j = $from; $j < $len; $j++ ) {
1711 + $c = $html[ $j ];
1712 + if ( '' !== $quote ) {
1713 + if ( $c === $quote ) {
1714 + $quote = '';
1715 + }
1716 + } elseif ( '"' === $c || "'" === $c ) {
1717 + $quote = $c;
1718 + } elseif ( '>' === $c ) {
1719 + return $j;
1720 + }
1721 + }
1722 + return null;
1185 1723 }
1186 1724 }