PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.7
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.7
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 1.1.3 1.1.4 All 33 releases
← All changes | includes/class-resource-hints-processor.php +637 -44 1.2.4 → 1.3.7 View file →
@@ -3,15 +3,18 @@
3 3 * Resource Hints processor — pure HTML transformer for resource hints.
4 4 *
5 5 * Given a fully-rendered page and the Preload module's options, it:
6 6 * 1. Ranks every eligible <img> by the largest declared size it can read —
7 - * width×height attributes, else the widest srcset candidate — and emits
7 + * width×height attributes, else the widest srcset candidate — boosted by
8 + * the author's own priority signals (fetchpriority="high", an explicit
9 + * loading="eager") and lightly weighted by document position, and emits
8 10 * a <link rel="preload" as="image" fetchpriority="high"> for the top N
9 11 * in the <head>, carrying srcset/sizes as imagesrcset/imagesizes so the
10 12 * browser can pick the right candidate — then adds fetchpriority="high"
11 - * to the <img> itself so it beats any loading="lazy" the theme set.
12 - * Ranking by size rather than document position: the first images on a
13 - * real page are usually header chrome, not the hero (#96).
13 + * to the <img> itself. Ranking by size rather than document position:
14 + * the first images on a real page are usually header chrome, not the
15 + * hero (#96). Images inside <footer>/<nav>/<aside>, images the theme
16 + * explicitly lazy-loads, and tiny images never compete (FBS-84576).
14 17 * 2. Emits <link rel="preconnect"> for detected web-font hosts
15 18 * (fonts.googleapis.com + fonts.gstatic.com) and any user-supplied
16 19 * hosts, deduped.
17 20 *
@@ -60,8 +63,20 @@
60 63 [ $html, $preload ] = self::build_lcp_preload( $html, $count, $exclusions );
61 64 $hints .= $preload;
62 65 }
63 66
67 + // The manual list runs AFTER the automatic pick so it can deduplicate
68 + // against it: a URL both name should carry ONE hint, not two. It exists
69 + // for the image the detector cannot see — most often a hero section's
70 + // CSS background-image, where the LCP element is a <div> with none of
71 + // the width/height/fetchpriority signals the scorer reads. On the site
72 + // that surfaced this, 3.3s of a 5.3s mobile LCP was pure discovery
73 + // delay for exactly such an image. (FBS-84578)
74 + $manual = array_filter( array_map( 'strval', (array) ( $opts['preload_images'] ?? array() ) ) );
75 + if ( ! empty( $manual ) ) {
76 + $hints .= self::build_manual_image_preloads( $manual, $hints );
77 + }
78 +
64 79 // Full-page eager promotion for Lazy-excluded heroes (FBS-83553 H2). The
65 80 // Lazy module only filters the_content/thumbnail/avatar/widget, so a
66 81 // theme/builder hero printed OUTSIDE those keeps WP core's
67 82 // loading="lazy". This pass runs over the whole document, so it can reach
@@ -80,26 +95,90 @@
80 95 return self::inject_into_head( $html, $hints );
81 96 }
82 97
83 98 /**
84 - * Strip core `loading="lazy"` and add `fetchpriority="high"` +
85 - * `decoding="async"` on every <img> whose tag matches one of the given
86 - * exclusion substrings. Mirrors what Lazy_Loader does for an excluded image
87 - * inside the_content, but page-wide so heroes outside it are covered too.
88 - * (FBS-83553 H2)
99 + * How many entries of the manual preload list are honoured. Preloading
100 + * competes with the page for its top network priority — a long list
101 + * inverts the benefit, so the cap is deliberately small.
102 + */
103 + private const MAX_MANUAL_PRELOADS = 3;
104 +
105 + /**
106 + * One `<link rel="preload" as="image">` per manual list entry.
89 107 *
108 + * Entries are full URLs or site-relative paths. Anything that is neither
109 + * (a data: URI, a bare word) is skipped rather than guessed at, and a URL
110 + * the automatic pick already emitted is skipped too — one hint per image,
111 + * whoever names it first.
112 + *
113 + * @param array<int,string> $urls The configured list.
114 + * @param string $existing_hints Hints already built this request.
115 + */
116 + private static function build_manual_image_preloads( array $urls, string $existing_hints ): string {
117 + /**
118 + * Filter the manual image-preload list before it is emitted.
119 + *
120 + * @param array<int,string> $urls Configured URLs, in panel order.
121 + */
122 + $urls = (array) apply_filters( 'xspeed_preload_images', $urls );
123 +
124 + $out = '';
125 + $seen = array();
126 + foreach ( $urls as $url ) {
127 + $url = trim( (string) $url );
128 + if ( '' === $url ) {
129 + continue;
130 + }
131 + // A full URL or a site-relative path; nothing else is guessable.
132 + $is_absolute = (bool) preg_match( '#^https?://#i', $url );
133 + $is_relative = '' !== $url && '/' === $url[0] && ( strlen( $url ) < 2 || '/' !== $url[1] );
134 + if ( ! $is_absolute && ! $is_relative ) {
135 + continue;
136 + }
137 + $href = esc_url( $url );
138 + if ( '' === $href || isset( $seen[ $href ] ) || false !== strpos( $existing_hints, 'href="' . $href . '"' ) ) {
139 + continue;
140 + }
141 + $seen[ $href ] = true;
142 + $out .= '<link rel="preload" as="image" href="' . $href . '" fetchpriority="high">';
143 + if ( count( $seen ) >= self::MAX_MANUAL_PRELOADS ) {
144 + break;
145 + }
146 + }
147 +
148 + return $out;
149 + }
150 +
151 + /**
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)
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 + *
90 162 * @param string $html Full page HTML.
91 163 * @param string[] $exclusions Substring patterns identifying above-the-fold heroes.
92 164 */
93 165 private static function promote_excluded_images( string $html, array $exclusions ): string {
94 - return (string) preg_replace_callback(
95 - '#<img\b(?:"[^"]*"|\'[^\']*\'|[^>"\'])*>#i',
96 - static function ( array $m ) use ( $exclusions ) {
97 - $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];
98 174 foreach ( $exclusions as $needle ) {
99 175 if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
100 176 $tag = (string) preg_replace( '#\s*\bloading=(["\'])\s*lazy\s*\1#i', '', $tag );
101 - $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 + }
102 181 if ( ! preg_match( '#\bdecoding=#i', $tag ) ) {
103 182 $tag = (string) preg_replace( '#<img\b#i', '<img decoding="async"', $tag, 1 );
104 183 }
105 184 return $tag;
@@ -106,10 +185,15 @@
106 185 }
107 186 }
108 187 return $tag;
109 188 },
110 - $html
189 + $html,
190 + -1,
191 + $count,
192 + PREG_OFFSET_CAPTURE
111 193 );
194 +
195 + return is_string( $result ) ? $result : $html;
112 196 }
113 197
114 198 /**
115 199 * Build preconnect <link>s for detected font hosts + user hosts.
@@ -187,23 +271,43 @@
187 271 // nothing — it just adds a high-priority request competing with the
188 272 // one that matters, and the feature reported success either way. The
189 273 // marker list and size gate were heuristics layered on top of the
190 274 // wrong primitive rather than replacing it. (#96)
191 - $candidates = array();
192 - if ( preg_match_all( '#<img\b[^>]*>#i', $html, $matches ) ) {
193 - foreach ( $matches[0] as $index => $tag ) {
275 + $candidates = array();
276 + // Markup hidden on arrival (a closed <details>, `hidden`, inline
277 + // display:none) cannot paint as LCP either. Preloading the hero of a
278 + // closed accordion spent the page's one High fetch on it. (#558)
279 + $skip_ranges = array_merge( self::chrome_container_ranges( $html ), Lazy_Loader::hidden_ranges( $html ) );
280 + // <img> indexes that can't be the LCP however they are marked: chrome,
281 + // hidden, or a logo/icon. Only these give up a stray `high`. (#558)
282 + $ruled_out = array();
283 + if ( preg_match_all( '#<img\b[^>]*>#i', $html, $matches, PREG_OFFSET_CAPTURE ) ) {
284 + foreach ( $matches[0] as $index => $match ) {
285 + [ $tag, $offset ] = $match;
286 +
194 287 // Skip anything the user excluded.
195 - $excluded = false;
196 - foreach ( $exclusions as $needle ) {
197 - if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
198 - $excluded = true;
199 - break;
200 - }
288 + if ( self::matches_any( $tag, $exclusions ) ) {
289 + continue;
201 290 }
202 - if ( $excluded ) {
291 +
292 + // An image inside <footer>/<nav>/<aside> is site chrome by
293 + // construction — a footer brand strip or FAQ illustration can
294 + // never be the LCP element, whatever size it declares. On the
295 + // FBS-84576 repro these decoys outranked the real hero three
296 + // times on one layout.
297 + if ( self::offset_in_ranges( $offset, $skip_ranges ) || Lazy_Loader::tag_is_hidden( $tag, 'img' ) ) {
298 + $ruled_out[ $index ] = true;
203 299 continue;
204 300 }
205 301
302 + // An image the theme explicitly lazy-loads is never the
303 + // intended LCP — the author has already said "this can wait".
304 + // Preloading it would contradict the markup and steal
305 + // bandwidth from the image that matters. (FBS-84576)
306 + if ( 'lazy' === strtolower( self::attr( $tag, 'loading' ) ) ) {
307 + continue;
308 + }
309 +
206 310 // Resolve the EFFECTIVE image URL. Page builders + JS lazy
207 311 // loaders park a placeholder (a data: URI or a 1px spacer) in
208 312 // `src` and the real URL in `data-src`, so the hero the browser
209 313 // actually paints is behind data-src. (FBS-83553 H1)
@@ -214,8 +318,9 @@
214 318
215 319 // Chrome markers / explicit opt-out / obviously-tiny images
216 320 // never compete. (FBS-83553 H1 "logo before hero".)
217 321 if ( self::looks_too_small( $tag ) ) {
322 + $ruled_out[ $index ] = true;
218 323 continue;
219 324 }
220 325
221 326 $candidates[] = array(
@@ -222,10 +327,11 @@
222 327 'tag' => $tag,
223 328 'src' => $src,
224 329 'srcset' => $srcset,
225 330 'sizes' => $sizes,
226 - 'score' => self::lcp_score( $tag, $srcset ),
331 + 'score' => self::weighted_score( self::lcp_score( $tag, $srcset ), $tag, $index ),
227 332 'order' => $index,
333 + 'offset' => $offset,
228 334 );
229 335 }
230 336 }
231 337
@@ -236,13 +342,51 @@
236 342 // the element that actually paints as LCP. It preloaded whatever <img>
237 343 // happened to be there — measured at 0ms against the feature switched
238 344 // off, while spending a high-priority fetch on the critical path — or,
239 345 // on a page with no <img> at all, emitted nothing. (#247)
240 - foreach ( self::background_candidates( $html, $exclusions ) as $bg ) {
346 + foreach ( self::background_candidates( $html, $exclusions, $skip_ranges ) as $bg ) {
241 347 $candidates[] = $bg;
242 348 }
243 349
350 + // PASS 1c — <video poster="…">. A full-screen hero video paints its
351 + // poster first, and that first frame IS the LCP; measured on a live
352 + // page, a preloaded poster cut the LCP load delay from 1.5 s to 21 ms.
353 + foreach ( self::video_poster_candidates( $html, $exclusions, $skip_ranges ) as $vp ) {
354 + $candidates[] = $vp;
355 + }
356 +
357 + // PASS 1d — background rules in inline <style> blocks. Page builders
358 + // put the hero's background-image in generated per-post CSS printed
359 + // inline (Elementor's `.elementor-N .elementor-element-X` rules), not
360 + // in a style attribute — so PASS 1b never saw the element that
361 + // actually paints as LCP on five of seven measured sites. External
362 + // stylesheets stay out for the same reasons as before (#247): fetching
363 + // CSS from an output-buffer pass costs more than the preload saves.
364 + foreach ( self::style_block_candidates( $html, $exclusions, $skip_ranges ) as $sb ) {
365 + $candidates[] = $sb;
366 + }
367 +
368 + // A background video with no poster, ahead of every candidate, is the
369 + // hero. Nothing in its box is preloadable, and every image after it
370 + // sits lower on the page. Preloading the first of those spent the one
371 + // high-priority fetch on an image below the fold, ahead of the CSS.
372 + // Those images also give up a stray `high` from the lazy pass.
373 + $video_at = self::background_video_offset( $html, $skip_ranges );
374 + if ( null !== $video_at ) {
375 + foreach ( $candidates as $i => $c ) {
376 + if ( $c['offset'] > $video_at ) {
377 + if ( empty( $c['background'] ) ) {
378 + $ruled_out[ $c['order'] ] = true;
379 + }
380 + unset( $candidates[ $i ] );
381 + }
382 + }
383 + }
384 +
244 385 if ( empty( $candidates ) ) {
386 + if ( null !== $video_at ) {
387 + $html = self::demote_images( $html, $ruled_out );
388 + }
245 389 return array( $html, '' );
246 390 }
247 391
248 392 // Rank by score, biggest first. Document order breaks ties, so two
@@ -286,14 +430,26 @@
286 430 // Rewrite only the winning tags. Counting occurrences rather than
287 431 // matching on tag text, because the same markup can legitimately
288 432 // appear more than once on a page and only the ranked instance should
289 433 // be promoted.
290 - $seen = -1;
291 - $html = preg_replace_callback(
434 + //
435 + // When an <img> wins, it is the page's one High image, so an image
436 + // that can't be the LCP (a logo, an icon, a hidden panel, chrome)
437 + // gives up any `high` it carries. That is usually the lazy pass handing
438 + // its slot to the first image in the_content. An image that merely scored
439 + // lower, or that the user kept out of the pick, keeps its hint: the
440 + // ranking can be wrong, and core or the theme may have named the real
441 + // hero. (#558)
442 + $demote = ! empty( $chosen ) || null !== $video_at ? $ruled_out : array();
443 + $seen = -1;
444 + $html = preg_replace_callback(
292 445 '#<img\b[^>]*>#i',
293 - static function ( array $m ) use ( &$seen, $chosen ) {
446 + static function ( array $m ) use ( &$seen, $chosen, $demote ) {
294 447 ++$seen;
295 448 if ( ! isset( $chosen[ $seen ] ) ) {
449 + if ( isset( $demote[ $seen ] ) && 'high' === strtolower( self::attr( $m[0], 'fetchpriority' ) ) ) {
450 + return (string) preg_replace( '#\s*(?<![-\w])fetchpriority\s*=\s*(["\']?)high\1#i', '', $m[0], 1 );
451 + }
296 452 return $m[0];
297 453 }
298 454 // Add fetchpriority="high" AND remove any loading="lazy" the
299 455 // theme / WP core left on the LCP image. fetchpriority="high"
@@ -308,8 +464,56 @@
308 464 return array( (string) $html, $preload );
309 465 }
310 466
311 467 /**
468 + * Byte offset of the first visible background video with no poster, or
469 + * null when the page has none.
470 + *
471 + * @param string $html Full page HTML.
472 + * @param array<int,array{0:int,1:int}> $skip_ranges Chrome and hidden spans.
473 + */
474 + private static function background_video_offset( string $html, array $skip_ranges ): ?int {
475 + $body = stripos( $html, '<body' );
476 + if ( ! preg_match_all( '#<video\b[^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE, false === $body ? 0 : $body ) ) {
477 + return null;
478 + }
479 + foreach ( $m[0] as [ $tag, $offset ] ) {
480 + if ( self::offset_in_ranges( $offset, $skip_ranges ) || Lazy_Loader::tag_is_hidden( $tag, 'video' ) ) {
481 + continue;
482 + }
483 + if ( Lazy_Loader::is_background_video_without_poster( $tag ) ) {
484 + return $offset;
485 + }
486 + }
487 + return null;
488 + }
489 +
490 + /**
491 + * Strip fetchpriority="high" from the <img> tags at the given indexes.
492 + *
493 + * @param string $html Page HTML.
494 + * @param array<int,bool> $indexes <img> indexes, in document order.
495 + */
496 + private static function demote_images( string $html, array $indexes ): string {
497 + if ( empty( $indexes ) ) {
498 + return $html;
499 + }
500 + $seen = -1;
501 + $out = preg_replace_callback(
502 + '#<img\b[^>]*>#i',
503 + static function ( array $m ) use ( &$seen, $indexes ) {
504 + ++$seen;
505 + if ( isset( $indexes[ $seen ] ) && 'high' === strtolower( self::attr( $m[0], 'fetchpriority' ) ) ) {
506 + return (string) preg_replace( '#\s*(?<![-\w])fetchpriority\s*=\s*(["\']?)high\1#i', '', $m[0], 1 );
507 + }
508 + return $m[0];
509 + },
510 + $html
511 + );
512 + return null === $out ? $html : $out;
513 + }
514 +
515 + /**
312 516 * Collect CSS `background-image` heroes as LCP candidates.
313 517 *
314 518 * Only INLINE `style` attributes are read. A background declared in an
315 519 * external stylesheet is invisible here by design: resolving it would mean
@@ -321,19 +525,28 @@
321 525 * Scores are the element's declared pixel area so a background competes
322 526 * against an <img> in the SAME units — the whole point being that the
323 527 * bigger of the two should win regardless of which kind it is.
324 528 *
325 - * @param string $html Full page HTML.
326 - * @param string[] $exclusions Substring patterns the user excluded.
327 - * @return array<int,array{tag:string,src:string,srcset:string,sizes:string,score:int,order:int,background:bool}>
529 + * @param string $html Full page HTML.
530 + * @param string[] $exclusions Substring patterns the user excluded.
531 + * @param array<int,array{0:int,1:int}> $skip_ranges Byte ranges of chrome containers.
532 + * @return array<int,array{tag:string,src:string,srcset:string,sizes:string,score:float,order:int,background:bool}>
328 533 */
329 - private static function background_candidates( string $html, array $exclusions ): array {
330 - if ( ! preg_match_all( '#<(?:div|section|header|figure|a|span|li|main|article|aside)\b[^>]*\sstyle\s*=\s*(["\']).*?\1[^>]*>#is', $html, $matches ) ) {
534 + private static function background_candidates( string $html, array $exclusions, array $skip_ranges ): array {
535 + if ( ! preg_match_all( '#<(?:div|section|header|figure|a|span|li|main|article|aside)\b[^>]*\sstyle\s*=\s*(["\']).*?\1[^>]*>#is', $html, $matches, PREG_OFFSET_CAPTURE ) ) {
331 536 return array();
332 537 }
333 538
334 539 $found = array();
335 - foreach ( $matches[0] as $index => $tag ) {
540 + foreach ( $matches[0] as $index => $match ) {
541 + [ $tag, $offset ] = $match;
542 +
543 + // The same chrome-container gate as <img>: a background painted
544 + // inside <footer>/<nav>/<aside> is never the hero. (FBS-84576)
545 + if ( self::offset_in_ranges( $offset, $skip_ranges ) ) {
546 + continue;
547 + }
548 +
336 549 $style = self::attr( $tag, 'style' );
337 550 if ( '' === $style || false === stripos( $style, 'background' ) ) {
338 551 continue;
339 552 }
@@ -368,12 +581,13 @@
368 581 'tag' => $tag,
369 582 'src' => $src,
370 583 'srcset' => '',
371 584 'sizes' => '',
372 - 'score' => $area,
585 + 'score' => (float) $area,
373 586 // Offset so a background never ties ahead of an <img> that
374 587 // appeared earlier in the document; ties still break on order.
375 588 'order' => 100000 + $index,
589 + 'offset' => $offset,
376 590 'background' => true,
377 591 );
378 592 }
379 593
@@ -380,8 +594,249 @@
380 594 return $found;
381 595 }
382 596
383 597 /**
598 + * Collect `<video poster="…">` first frames as LCP candidates.
599 + *
600 + * The poster is what the viewer sees until (and unless) the video plays —
601 + * on a background-video hero, delayed by the Lazy module, it is the ONLY
602 + * frame the initial paint has. Scored like a background: the element's
603 + * declared inline-style area, or the unknown-size floor, with the order
604 + * offset past every <img> so a poster never ties ahead of one.
605 + *
606 + * @param string $html Full page HTML.
607 + * @param string[] $exclusions Substring patterns the user excluded.
608 + * @param array<int,array{0:int,1:int}> $skip_ranges Byte ranges of chrome containers.
609 + * @return array<int,array{tag:string,src:string,srcset:string,sizes:string,score:float,order:int,background:bool}>
610 + */
611 + private static function video_poster_candidates( string $html, array $exclusions, array $skip_ranges ): array {
612 + if ( ! preg_match_all( '#<video\b[^>]*\bposter\s*=\s*(["\'])(.*?)\1[^>]*>#i', $html, $matches, PREG_OFFSET_CAPTURE ) ) {
613 + return array();
614 + }
615 +
616 + $found = array();
617 + foreach ( $matches[0] as $index => $match ) {
618 + [ $tag, $offset ] = $match;
619 + $src = trim( html_entity_decode( $matches[2][ $index ][0], ENT_QUOTES ) );
620 + if ( '' === $src || 0 === stripos( $src, 'data:' ) ) {
621 + continue;
622 + }
623 + if ( self::offset_in_ranges( $offset, $skip_ranges ) ) {
624 + continue;
625 + }
626 + foreach ( $exclusions as $needle ) {
627 + if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
628 + continue 2;
629 + }
630 + }
631 + if ( self::looks_too_small( $tag ) ) {
632 + continue;
633 + }
634 +
635 + $area = self::style_area( self::attr( $tag, 'style' ) );
636 + if ( 0 === $area ) {
637 + $area = self::UNKNOWN_SIZE_SCORE;
638 + }
639 +
640 + $found[] = array(
641 + 'tag' => $tag,
642 + 'src' => $src,
643 + 'srcset' => '',
644 + 'sizes' => '',
645 + 'score' => (float) $area,
646 + 'order' => 100000 + $index,
647 + 'offset' => $offset,
648 + 'background' => true,
649 + );
650 + }
651 +
652 + return $found;
653 + }
654 +
655 + /**
656 + * How many <style>-block background rules are considered per page. The
657 + * scan is linear, but each rule costs one class-lookup pass over the
658 + * body, so a pathological page (thousands of generated rules) is capped
659 + * rather than trusted.
660 + */
661 + private const STYLE_RULE_BUDGET = 40;
662 +
663 + /**
664 + * Collect background-image rules from inline <style> blocks whose
665 + * selector matches an element in the body.
666 + *
667 + * The match is deliberately narrow: the rule's RIGHTMOST simple selector
668 + * must carry a class or id, and the first element in the body bearing it
669 + * (outside chrome containers) is taken as the painted element. Rules
670 + * inside @media (or any other at-rule block) are skipped — a desktop-only
671 + * background preloaded on mobile is a wasted high-priority fetch, and the
672 + * markup gives no viewport to resolve the query against.
673 + *
674 + * @param string $html Full page HTML.
675 + * @param string[] $exclusions Substring patterns the user excluded.
676 + * @param array<int,array{0:int,1:int}> $skip_ranges Byte ranges of chrome containers.
677 + * @return array<int,array{tag:string,src:string,srcset:string,sizes:string,score:float,order:int,background:bool}>
678 + */
679 + private static function style_block_candidates( string $html, array $exclusions, array $skip_ranges ): array {
680 + if ( ! preg_match_all( '#<style\b[^>]*>(.*?)</style\s*>#is', $html, $blocks ) ) {
681 + return array();
682 + }
683 +
684 + $found = array();
685 + $budget = self::STYLE_RULE_BUDGET;
686 + foreach ( $blocks[1] as $css ) {
687 + if ( $budget <= 0 ) {
688 + break;
689 + }
690 + $css = self::strip_at_rule_blocks( $css );
691 + if ( false === stripos( $css, 'url(' ) ) {
692 + continue;
693 + }
694 + // One flat rule at a time: selector list up to '{', body to '}'.
695 + if ( ! preg_match_all( '#(?:^|})\s*([^{}]{1,512})\{([^{}]*)\}#s', $css, $rules, PREG_SET_ORDER ) ) {
696 + continue;
697 + }
698 + foreach ( $rules as $rule ) {
699 + if ( $budget <= 0 ) {
700 + break 2;
701 + }
702 + if ( false === stripos( $rule[2], 'url(' ) ) {
703 + continue;
704 + }
705 + $src = self::background_url( $rule[2] );
706 + if ( '' === $src ) {
707 + continue;
708 + }
709 + --$budget;
710 + // First selector of the list, rightmost compound of it.
711 + $selector = trim( (string) strtok( $rule[1], ',' ) );
712 + $parts = preg_split( '#[\s>+~]+#', $selector );
713 + $last = (string) end( $parts );
714 + // The last class or id token of that compound. Pseudo-classes
715 + // (:hover, ::before) mean the background is not the initial
716 + // paint, so they disqualify the rule.
717 + if ( false !== strpos( $last, ':' ) ) {
718 + continue;
719 + }
720 + if ( ! preg_match( '#([.\#])([-\w]+)$#', $last, $tok ) ) {
721 + continue;
722 + }
723 + $el = '.' === $tok[1]
724 + ? self::first_element_with_class( $html, $tok[2], $skip_ranges )
725 + : self::first_element_with_id( $html, $tok[2], $skip_ranges );
726 + if ( null === $el ) {
727 + continue;
728 + }
729 + [ $tag, $offset ] = $el;
730 + foreach ( $exclusions as $needle ) {
731 + if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
732 + continue 2;
733 + }
734 + }
735 + if ( self::looks_too_small( $tag ) ) {
736 + continue;
737 + }
738 + $area = self::style_area( self::attr( $tag, 'style' ) );
739 + if ( 0 === $area ) {
740 + $area = self::UNKNOWN_SIZE_SCORE;
741 + }
742 + $found[] = array(
743 + 'tag' => $tag,
744 + 'src' => $src,
745 + 'srcset' => '',
746 + 'sizes' => '',
747 + 'score' => (float) $area,
748 + // Offset past the inline-style backgrounds: a rule-matched
749 + // background is one inference step less certain, so it must
750 + // never tie ahead of one read straight off the element.
751 + 'order' => 200000 + $offset,
752 + 'offset' => $offset,
753 + 'background' => true,
754 + );
755 + }
756 + }
757 +
758 + return $found;
759 + }
760 +
761 + /**
762 + * CSS with every at-rule BLOCK (@media, @supports, @container, …) removed,
763 + * by brace depth — a regex cannot pair nested braces. Flat at-rules
764 + * (@import, @charset) have no block and pass through harmlessly.
765 + */
766 + private static function strip_at_rule_blocks( string $css ): string {
767 + $out = '';
768 + $len = strlen( $css );
769 + $i = 0;
770 + while ( $i < $len ) {
771 + $at = strpos( $css, '@', $i );
772 + if ( false === $at ) {
773 + return $out . substr( $css, $i );
774 + }
775 + $brace = strpos( $css, '{', $at );
776 + $semi = strpos( $css, ';', $at );
777 + $out .= substr( $css, $i, $at - $i );
778 + if ( false === $brace || ( false !== $semi && $semi < $brace ) ) {
779 + // Flat at-rule — skip to its semicolon (or end).
780 + $i = false === $semi ? $len : $semi + 1;
781 + continue;
782 + }
783 + // Block at-rule — skip to its matching close brace.
784 + $depth = 1;
785 + $i = $brace + 1;
786 + while ( $i < $len && $depth > 0 ) {
787 + $c = $css[ $i ];
788 + if ( '{' === $c ) {
789 + ++$depth;
790 + } elseif ( '}' === $c ) {
791 + --$depth;
792 + }
793 + ++$i;
794 + }
795 + }
796 + return $out;
797 + }
798 +
799 + /**
800 + * The first element in the BODY carrying $class (outside chrome ranges),
801 + * as [tag, offset], or null. Body-only, so a head <meta> can never match
802 + * and a hit's offset is comparable with the chrome ranges.
803 + *
804 + * @return array{0:string,1:int}|null
805 + */
806 + private static function first_element_with_class( string $html, string $class, array $skip_ranges ): ?array {
807 + $body = stripos( $html, '<body' );
808 + $from = false === $body ? 0 : $body;
809 + if ( ! preg_match_all( '#<[a-z][^>]*\bclass\s*=\s*(["\'])[^"\']*(?<![-\w])' . preg_quote( $class, '#' ) . '(?![-\w])[^"\']*\1[^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE, $from ) ) {
810 + return null;
811 + }
812 + foreach ( $m[0] as $match ) {
813 + if ( ! self::offset_in_ranges( $match[1], $skip_ranges ) ) {
814 + return array( $match[0], $match[1] );
815 + }
816 + }
817 + return null;
818 + }
819 +
820 + /**
821 + * The first element carrying id="$id" (outside chrome ranges), as
822 + * [tag, offset], or null.
823 + *
824 + * @return array{0:string,1:int}|null
825 + */
826 + private static function first_element_with_id( string $html, string $id, array $skip_ranges ): ?array {
827 + $body = stripos( $html, '<body' );
828 + $from = false === $body ? 0 : $body;
829 + if ( ! preg_match( '#<[a-z][^>]*\bid\s*=\s*(["\'])' . preg_quote( $id, '#' ) . '\1[^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE, $from ) ) {
830 + return null;
831 + }
832 + if ( self::offset_in_ranges( $m[0][1], $skip_ranges ) ) {
833 + return null;
834 + }
835 + return array( $m[0][0], $m[0][1] );
836 + }
837 +
838 + /**
384 839 * Pull a real image URL out of a `background`/`background-image` declaration.
385 840 *
386 841 * Returns '' for anything with nothing to fetch: a gradient (which is a
387 842 * background-image but not a resource), a data: URI, or `none`.
@@ -450,13 +905,13 @@
450 905 *
451 906 * @param string $tag The full <img> tag.
452 907 * @param string $srcset Resolved srcset (may come from data-srcset).
453 908 */
454 - private static function lcp_score( string $tag, string $srcset ): int {
909 + private static function lcp_score( string $tag, string $srcset ): float {
455 910 $w = self::attr( $tag, 'width' );
456 911 $h = self::attr( $tag, 'height' );
457 912 if ( '' !== $w && '' !== $h && is_numeric( $w ) && is_numeric( $h ) ) {
458 - return (int) $w * (int) $h;
913 + return (float) ( (int) $w * (int) $h );
459 914 }
460 915
461 916 $widest = self::widest_srcset_width( $srcset );
462 917 if ( $widest > 0 ) {
@@ -466,15 +921,142 @@
466 921 // 1024w sidebar thumbnail (1 048 576) beat a declared 1200×600
467 922 // hero (720 000) — a regression on exactly the mixed pages that
468 923 // document order used to get right, since the hero usually comes
469 924 // first. Assuming a 16:9 box keeps both sides in the same units.
470 - return (int) round( $widest * $widest * self::ASSUMED_ASPECT_RATIO );
925 + return round( $widest * $widest * self::ASSUMED_ASPECT_RATIO );
471 926 }
472 927
473 - return self::UNKNOWN_SIZE_SCORE;
928 + return (float) self::UNKNOWN_SIZE_SCORE;
474 929 }
475 930
476 931 /**
932 + * Fold the author's own priority signals and document position into an
933 + * area score. (FBS-84576)
934 + *
935 + * Boosts are ADDITIVE, in area units, so they can rescue an image whose
936 + * size the markup doesn't declare: a hero with no width/height and no
937 + * `w`-descriptor srcset scores UNKNOWN_SIZE_SCORE, and multiplying that
938 + * by any factor still loses to a 548×136 logo that declares itself. This
939 + * is exactly the live miss — the real hero carried loading="eager"
940 + * fetchpriority="high" and lost to three dimension-declaring decoys.
941 + *
942 + * - fetchpriority="high" is the strongest signal there is: the author
943 + * (or WP core's own LCP detection) has already named this image the
944 + * hero. Worth a hero-sized area.
945 + * - An EXPLICIT loading="eager" is a weaker but deliberate "load me
946 + * now" (the default is eager, so writing it out is a choice).
947 + *
948 + * Position is a light multiplicative weight — earlier is better, but the
949 + * spread is capped well under 5× so it can only break near-ties, never
950 + * outrank a genuinely larger image further down (the logo-vs-hero case).
951 + *
952 + * @param float $score Base area score from lcp_score() / style_area().
953 + * @param string $tag The candidate's full tag (for the signal attrs).
954 + * @param int $order Document-order index of the candidate.
955 + */
956 + private static function weighted_score( float $score, string $tag, int $order ): float {
957 + if ( 'high' === strtolower( self::attr( $tag, 'fetchpriority' ) ) ) {
958 + $score += self::FETCHPRIORITY_HIGH_BOOST;
959 + }
960 + if ( 'eager' === strtolower( self::attr( $tag, 'loading' ) ) ) {
961 + $score += self::EAGER_BOOST;
962 + }
963 + return $score * self::position_weight( $order );
964 + }
965 +
966 + /**
967 + * Document-position weight: 1.25 for the first image, easing to 1.0 by
968 + * the tenth. The whole spread is 25%, far under the 5× area difference it
969 + * must never override — it exists only to keep the old first-wins
970 + * behaviour for images we can't tell apart.
971 + */
972 + private static function position_weight( int $order ): float {
973 + return 1.0 + 0.25 * max( 0.0, 1.0 - $order / 10 );
974 + }
975 +
976 + /**
977 + * Area-unit boost for fetchpriority="high" — roughly a 940×530 hero, so
978 + * an explicitly-marked image outranks any mid-page decoy even when its
979 + * own size is unreadable, while a genuinely huge unmarked image can still
980 + * beat a marked small one.
981 + */
982 + private const FETCHPRIORITY_HIGH_BOOST = 500000.0;
983 +
984 + /**
985 + * Area-unit boost for an explicit loading="eager" — roughly 420×240,
986 + * enough to break ties in favour of the author's intent without letting
987 + * an eager logo outrank a plain hero.
988 + */
989 + private const EAGER_BOOST = 100000.0;
990 +
991 + /**
992 + * Byte ranges of <footer>/<nav>/<aside> regions. Nesting-aware per tag
993 + * name (a nav inside a nav extends the range); an unclosed open tag
994 + * poisons through to the end of the document, which errs on the side of
995 + * not preloading — the safe direction, since a wrong preload is worse
996 + * than none. (FBS-84576)
997 + *
998 + * @return array<int,array{0:int,1:int}> [start, end] byte offsets.
999 + */
1000 + private static function chrome_container_ranges( string $html ): array {
1001 + $ranges = array();
1002 + foreach ( array( 'footer', 'nav', 'aside' ) as $name ) {
1003 + // (?=[\s/>]) rather than \b: a word boundary sits before the `-`
1004 + // of a custom element, so `<nav\b` would swallow `<nav-menu>`.
1005 + if ( ! preg_match_all( '#<(/?)' . $name . '(?=[\s/>])[^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE ) ) {
1006 + continue;
1007 + }
1008 + $depth = 0;
1009 + $start = 0;
1010 + foreach ( $m[0] as $i => $match ) {
1011 + $closing = '' !== $m[1][ $i ][0];
1012 + if ( ! $closing ) {
1013 + if ( 0 === $depth ) {
1014 + $start = $match[1];
1015 + }
1016 + ++$depth;
1017 + } elseif ( $depth > 0 ) {
1018 + --$depth;
1019 + if ( 0 === $depth ) {
1020 + $ranges[] = array( $start, $match[1] );
1021 + }
1022 + }
1023 + }
1024 + if ( $depth > 0 ) {
1025 + $ranges[] = array( $start, strlen( $html ) );
1026 + }
1027 + }
1028 + return $ranges;
1029 + }
1030 +
1031 + /**
1032 + * Does a tag contain any of the given substring patterns?
1033 + *
1034 + * @param string[] $patterns
1035 + */
1036 + private static function matches_any( string $tag, array $patterns ): bool {
1037 + foreach ( $patterns as $needle ) {
1038 + if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
1039 + return true;
1040 + }
1041 + }
1042 + return false;
1043 + }
1044 +
1045 + /** Does a byte offset fall inside any of the given [start, end] ranges? */
1046 + private static function offset_in_ranges( int $offset, array $ranges ): bool {
1047 + foreach ( $ranges as $range ) {
1048 + // >= on the start: a closed <details> span from
1049 + // Lazy_Loader::hidden_ranges() opens right at the first image
1050 + // after its <summary>.
1051 + if ( $offset >= $range[0] && $offset < $range[1] ) {
1052 + return true;
1053 + }
1054 + }
1055 + return false;
1056 + }
1057 +
1058 + /**
477 1059 * Score for an image whose size we can't read at all.
478 1060 *
479 1061 * Deliberately non-zero: an unmeasurable image must still beat nothing and
480 1062 * still be preloadable on a page where no image declares its size. But it
@@ -635,13 +1217,21 @@
635 1217 */
636 1218 private const NON_HERO_MARKERS = array( 'logo', 'icon', 'avatar', 'gravatar', 'spinner', 'emoji', 'site-icon', 'custom-logo' );
637 1219
638 1220 /**
1221 + * Below this declared area (px²) an image is a badge/thumb/divider, never
1222 + * an LCP hero — 10 000 is a 100×100 square, or a 500×20 strip. Applied
1223 + * only when BOTH dimensions are readable. (FBS-84576)
1224 + */
1225 + private const MIN_LCP_AREA = 10000;
1226 +
1227 + /**
639 1228 * Is this <img> too small / too chrome-like to be the LCP hero? True when
640 1229 * either (a) it carries a logo/icon/avatar marker, (b) an explicit
641 - * `data-no-lcp` opt-out, or (c) BOTH width and height are present and both
642 - * are ≤ the threshold. Missing dimensions are NOT guessed — an image whose
643 - * size we can't read still competes. (FBS-83553 H1 "logo before hero".)
1230 + * `data-no-lcp` opt-out, or (c) BOTH width and height are present and
1231 + * both are ≤ the dimension threshold, or their area is under
1232 + * MIN_LCP_AREA. Missing dimensions are NOT guessed — an image whose size
1233 + * we can't read still competes. (FBS-83553 H1 "logo before hero".)
644 1234 */
645 1235 private static function looks_too_small( string $tag ): bool {
646 1236 if ( false !== stripos( $tag, 'data-no-lcp' ) ) {
647 1237 return true;
@@ -657,8 +1247,11 @@
657 1247 $w = self::attr( $tag, 'width' );
658 1248 $h = self::attr( $tag, 'height' );
659 1249 if ( '' === $w || '' === $h || ! is_numeric( $w ) || ! is_numeric( $h ) ) {
660 1250 return false; // unknown size — don't guess; let it compete.
1251 + }
1252 + if ( (int) $w * (int) $h < self::MIN_LCP_AREA ) {
1253 + return true;
661 1254 }
662 1255 return (int) $w <= self::MIN_LCP_DIMENSION && (int) $h <= self::MIN_LCP_DIMENSION;
663 1256 }
664 1257