PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.3
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.3
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 1.1.5 1.1.6 1.1.7 1.1.8 All 29 releases
← All changes | includes/class-resource-hints-processor.php +377 -16 1.1.71.3.3 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,8 +95,61 @@
80 95 return self::inject_into_head( $html, $hints );
81 96 }
82 97
83 98 /**
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.
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 + /**
84 152 * Strip core `loading="lazy"` and add `fetchpriority="high"` +
85 153 * `decoding="async"` on every <img> whose tag matches one of the given
86 154 * exclusion substrings. Mirrors what Lazy_Loader does for an excluded image
87 155 * inside the_content, but page-wide so heroes outside it are covered too.
@@ -187,11 +255,14 @@
187 255 // nothing — it just adds a high-priority request competing with the
188 256 // one that matters, and the feature reported success either way. The
189 257 // marker list and size gate were heuristics layered on top of the
190 258 // 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 ) {
259 + $candidates = array();
260 + $skip_ranges = self::chrome_container_ranges( $html );
261 + if ( preg_match_all( '#<img\b[^>]*>#i', $html, $matches, PREG_OFFSET_CAPTURE ) ) {
262 + foreach ( $matches[0] as $index => $match ) {
263 + [ $tag, $offset ] = $match;
264 +
194 265 // Skip anything the user excluded.
195 266 $excluded = false;
196 267 foreach ( $exclusions as $needle ) {
197 268 if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
@@ -202,8 +273,25 @@
202 273 if ( $excluded ) {
203 274 continue;
204 275 }
205 276
277 + // An image inside <footer>/<nav>/<aside> is site chrome by
278 + // construction — a footer brand strip or FAQ illustration can
279 + // never be the LCP element, whatever size it declares. On the
280 + // FBS-84576 repro these decoys outranked the real hero three
281 + // times on one layout.
282 + if ( self::offset_in_ranges( $offset, $skip_ranges ) ) {
283 + continue;
284 + }
285 +
286 + // An image the theme explicitly lazy-loads is never the
287 + // intended LCP — the author has already said "this can wait".
288 + // Preloading it would contradict the markup and steal
289 + // bandwidth from the image that matters. (FBS-84576)
290 + if ( 'lazy' === strtolower( self::attr( $tag, 'loading' ) ) ) {
291 + continue;
292 + }
293 +
206 294 // Resolve the EFFECTIVE image URL. Page builders + JS lazy
207 295 // loaders park a placeholder (a data: URI or a 1px spacer) in
208 296 // `src` and the real URL in `data-src`, so the hero the browser
209 297 // actually paints is behind data-src. (FBS-83553 H1)
@@ -222,14 +310,26 @@
222 310 'tag' => $tag,
223 311 'src' => $src,
224 312 'srcset' => $srcset,
225 313 'sizes' => $sizes,
226 - 'score' => self::lcp_score( $tag, $srcset ),
314 + 'score' => self::weighted_score( self::lcp_score( $tag, $srcset ), $tag, $index ),
227 315 'order' => $index,
228 316 );
229 317 }
230 318 }
231 319
320 + // PASS 1b — the same for CSS background images.
321 + //
322 + // On a page builder the hero is usually a background-image on the
323 + // section, not an <img>, so an <img>-only candidate set never contained
324 + // the element that actually paints as LCP. It preloaded whatever <img>
325 + // happened to be there — measured at 0ms against the feature switched
326 + // off, while spending a high-priority fetch on the critical path — or,
327 + // on a page with no <img> at all, emitted nothing. (#247)
328 + foreach ( self::background_candidates( $html, $exclusions, $skip_ranges ) as $bg ) {
329 + $candidates[] = $bg;
330 + }
331 +
232 332 if ( empty( $candidates ) ) {
233 333 return array( $html, '' );
234 334 }
235 335
@@ -261,9 +361,15 @@
261 361 );
262 362 if ( ! $already ) {
263 363 $preload .= self::preload_link( $w['src'], $w['srcset'], $w['sizes'] );
264 364 }
265 - $chosen[ $w['order'] ] = true;
365 + // Only <img> winners are promoted in PASS 2 — there is no
366 + // fetchpriority/loading attribute to fix on a background element,
367 + // and its `order` is offset past every <img> index precisely so it
368 + // can never select one for rewriting.
369 + if ( empty( $w['background'] ) ) {
370 + $chosen[ $w['order'] ] = true;
371 + }
266 372 }
267 373
268 374 // Rewrite only the winning tags. Counting occurrences rather than
269 375 // matching on tag text, because the same markup can legitimately
@@ -290,8 +396,142 @@
290 396 return array( (string) $html, $preload );
291 397 }
292 398
293 399 /**
400 + * Collect CSS `background-image` heroes as LCP candidates.
401 + *
402 + * Only INLINE `style` attributes are read. A background declared in an
403 + * external stylesheet is invisible here by design: resolving it would mean
404 + * fetching and parsing CSS from inside an output-buffer pass, and the URL a
405 + * selector resolves to depends on cascade order we cannot evaluate from
406 + * markup. Builders that put the hero in a generated per-post stylesheet are
407 + * therefore still unserved — worth doing, but not at this cost. (#247)
408 + *
409 + * Scores are the element's declared pixel area so a background competes
410 + * against an <img> in the SAME units — the whole point being that the
411 + * bigger of the two should win regardless of which kind it is.
412 + *
413 + * @param string $html Full page HTML.
414 + * @param string[] $exclusions Substring patterns the user excluded.
415 + * @param array<int,array{0:int,1:int}> $skip_ranges Byte ranges of chrome containers.
416 + * @return array<int,array{tag:string,src:string,srcset:string,sizes:string,score:float,order:int,background:bool}>
417 + */
418 + private static function background_candidates( string $html, array $exclusions, array $skip_ranges ): array {
419 + 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 ) ) {
420 + return array();
421 + }
422 +
423 + $found = array();
424 + foreach ( $matches[0] as $index => $match ) {
425 + [ $tag, $offset ] = $match;
426 +
427 + // The same chrome-container gate as <img>: a background painted
428 + // inside <footer>/<nav>/<aside> is never the hero. (FBS-84576)
429 + if ( self::offset_in_ranges( $offset, $skip_ranges ) ) {
430 + continue;
431 + }
432 +
433 + $style = self::attr( $tag, 'style' );
434 + if ( '' === $style || false === stripos( $style, 'background' ) ) {
435 + continue;
436 + }
437 +
438 + $src = self::background_url( $style );
439 + if ( '' === $src ) {
440 + continue;
441 + }
442 +
443 + foreach ( $exclusions as $needle ) {
444 + if ( '' !== $needle && false !== stripos( $tag, $needle ) ) {
445 + continue 2;
446 + }
447 + }
448 +
449 + // Same chrome/opt-out gates as <img>. A logo painted as a background
450 + // is no more the hero than a logo in an <img>.
451 + if ( self::looks_too_small( $tag ) ) {
452 + continue;
453 + }
454 +
455 + $area = self::style_area( $style );
456 + if ( 0 === $area ) {
457 + // Nothing readable. Deliberately non-zero for the same reason
458 + // UNKNOWN_SIZE_SCORE is: an unmeasurable background must still
459 + // beat nothing on a page that declares no sizes at all, while
460 + // losing to anything we can actually measure.
461 + $area = self::UNKNOWN_SIZE_SCORE;
462 + }
463 +
464 + $found[] = array(
465 + 'tag' => $tag,
466 + 'src' => $src,
467 + 'srcset' => '',
468 + 'sizes' => '',
469 + 'score' => (float) $area,
470 + // Offset so a background never ties ahead of an <img> that
471 + // appeared earlier in the document; ties still break on order.
472 + 'order' => 100000 + $index,
473 + 'background' => true,
474 + );
475 + }
476 +
477 + return $found;
478 + }
479 +
480 + /**
481 + * Pull a real image URL out of a `background`/`background-image` declaration.
482 + *
483 + * Returns '' for anything with nothing to fetch: a gradient (which is a
484 + * background-image but not a resource), a data: URI, or `none`.
485 + */
486 + private static function background_url( string $style ): string {
487 + // Decode BEFORE parsing. Builders emit the url() quotes HTML-encoded
488 + // inside a style attribute (url(&quot;/hero.jpg&quot;)), and `&quot;`
489 + // carries a semicolon — so splitting the declaration on `;` first
490 + // truncated the value to `url(&quot` and found no URL at all.
491 + $style = html_entity_decode( $style, ENT_QUOTES );
492 +
493 + if ( ! preg_match( '#background(?:-image)?\s*:\s*((?:[^;\'"]|"[^"]*"|\'[^\']*\')+)#i', $style, $decl ) ) {
494 + return '';
495 + }
496 + if ( ! preg_match( '#url\(\s*(["\']?)(.*?)\1\s*\)#is', $decl[1], $m ) ) {
497 + return '';
498 + }
499 + $url = trim( $m[2] );
500 + if ( '' === $url || 0 === stripos( $url, 'data:' ) ) {
501 + return '';
502 + }
503 + return $url;
504 + }
505 +
506 + /**
507 + * Declared pixel area from an inline style, or 0 when it can't be read.
508 + *
509 + * Only px is honoured. A percentage or viewport unit resolves against a
510 + * containing block we cannot see from markup, and guessing one produced the
511 + * wrong winner more often than declining to.
512 + */
513 + private static function style_area( string $style ): int {
514 + $w = self::style_px( $style, 'width' );
515 + $h = self::style_px( $style, 'height' );
516 + if ( $w > 0 && $h > 0 ) {
517 + return $w * $h;
518 + }
519 + if ( $w > 0 ) {
520 + return (int) round( $w * $w * self::ASSUMED_ASPECT_RATIO );
521 + }
522 + return 0;
523 + }
524 +
525 + /** One px-valued CSS length from an inline style, or 0. */
526 + private static function style_px( string $style, string $prop ): int {
527 + if ( preg_match( '#(?:^|;)\s*' . preg_quote( $prop, '#' ) . '\s*:\s*(\d+(?:\.\d+)?)px#i', $style, $m ) ) {
528 + return (int) round( (float) $m[1] );
529 + }
530 + return 0;
531 + }
532 +
533 + /**
294 534 * How likely is this <img> to be the LCP element? Higher wins.
295 535 *
296 536 * Rendered area is the best available proxy, and we can only read what the
297 537 * markup declares:
@@ -307,13 +547,13 @@
307 547 *
308 548 * @param string $tag The full <img> tag.
309 549 * @param string $srcset Resolved srcset (may come from data-srcset).
310 550 */
311 - private static function lcp_score( string $tag, string $srcset ): int {
551 + private static function lcp_score( string $tag, string $srcset ): float {
312 552 $w = self::attr( $tag, 'width' );
313 553 $h = self::attr( $tag, 'height' );
314 554 if ( '' !== $w && '' !== $h && is_numeric( $w ) && is_numeric( $h ) ) {
315 - return (int) $w * (int) $h;
555 + return (float) ( (int) $w * (int) $h );
316 556 }
317 557
318 558 $widest = self::widest_srcset_width( $srcset );
319 559 if ( $widest > 0 ) {
@@ -323,15 +563,125 @@
323 563 // 1024w sidebar thumbnail (1 048 576) beat a declared 1200×600
324 564 // hero (720 000) — a regression on exactly the mixed pages that
325 565 // document order used to get right, since the hero usually comes
326 566 // first. Assuming a 16:9 box keeps both sides in the same units.
327 - return (int) round( $widest * $widest * self::ASSUMED_ASPECT_RATIO );
567 + return round( $widest * $widest * self::ASSUMED_ASPECT_RATIO );
328 568 }
329 569
330 - return self::UNKNOWN_SIZE_SCORE;
570 + return (float) self::UNKNOWN_SIZE_SCORE;
331 571 }
332 572
333 573 /**
574 + * Fold the author's own priority signals and document position into an
575 + * area score. (FBS-84576)
576 + *
577 + * Boosts are ADDITIVE, in area units, so they can rescue an image whose
578 + * size the markup doesn't declare: a hero with no width/height and no
579 + * `w`-descriptor srcset scores UNKNOWN_SIZE_SCORE, and multiplying that
580 + * by any factor still loses to a 548×136 logo that declares itself. This
581 + * is exactly the live miss — the real hero carried loading="eager"
582 + * fetchpriority="high" and lost to three dimension-declaring decoys.
583 + *
584 + * - fetchpriority="high" is the strongest signal there is: the author
585 + * (or WP core's own LCP detection) has already named this image the
586 + * hero. Worth a hero-sized area.
587 + * - An EXPLICIT loading="eager" is a weaker but deliberate "load me
588 + * now" (the default is eager, so writing it out is a choice).
589 + *
590 + * Position is a light multiplicative weight — earlier is better, but the
591 + * spread is capped well under 5× so it can only break near-ties, never
592 + * outrank a genuinely larger image further down (the logo-vs-hero case).
593 + *
594 + * @param float $score Base area score from lcp_score() / style_area().
595 + * @param string $tag The candidate's full tag (for the signal attrs).
596 + * @param int $order Document-order index of the candidate.
597 + */
598 + private static function weighted_score( float $score, string $tag, int $order ): float {
599 + if ( 'high' === strtolower( self::attr( $tag, 'fetchpriority' ) ) ) {
600 + $score += self::FETCHPRIORITY_HIGH_BOOST;
601 + }
602 + if ( 'eager' === strtolower( self::attr( $tag, 'loading' ) ) ) {
603 + $score += self::EAGER_BOOST;
604 + }
605 + return $score * self::position_weight( $order );
606 + }
607 +
608 + /**
609 + * Document-position weight: 1.25 for the first image, easing to 1.0 by
610 + * the tenth. The whole spread is 25%, far under the 5× area difference it
611 + * must never override — it exists only to keep the old first-wins
612 + * behaviour for images we can't tell apart.
613 + */
614 + private static function position_weight( int $order ): float {
615 + return 1.0 + 0.25 * max( 0.0, 1.0 - $order / 10 );
616 + }
617 +
618 + /**
619 + * Area-unit boost for fetchpriority="high" — roughly a 940×530 hero, so
620 + * an explicitly-marked image outranks any mid-page decoy even when its
621 + * own size is unreadable, while a genuinely huge unmarked image can still
622 + * beat a marked small one.
623 + */
624 + private const FETCHPRIORITY_HIGH_BOOST = 500000.0;
625 +
626 + /**
627 + * Area-unit boost for an explicit loading="eager" — roughly 420×240,
628 + * enough to break ties in favour of the author's intent without letting
629 + * an eager logo outrank a plain hero.
630 + */
631 + private const EAGER_BOOST = 100000.0;
632 +
633 + /**
634 + * Byte ranges of <footer>/<nav>/<aside> regions. Nesting-aware per tag
635 + * name (a nav inside a nav extends the range); an unclosed open tag
636 + * poisons through to the end of the document, which errs on the side of
637 + * not preloading — the safe direction, since a wrong preload is worse
638 + * than none. (FBS-84576)
639 + *
640 + * @return array<int,array{0:int,1:int}> [start, end] byte offsets.
641 + */
642 + private static function chrome_container_ranges( string $html ): array {
643 + $ranges = array();
644 + foreach ( array( 'footer', 'nav', 'aside' ) as $name ) {
645 + // (?=[\s/>]) rather than \b: a word boundary sits before the `-`
646 + // of a custom element, so `<nav\b` would swallow `<nav-menu>`.
647 + if ( ! preg_match_all( '#<(/?)' . $name . '(?=[\s/>])[^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE ) ) {
648 + continue;
649 + }
650 + $depth = 0;
651 + $start = 0;
652 + foreach ( $m[0] as $i => $match ) {
653 + $closing = '' !== $m[1][ $i ][0];
654 + if ( ! $closing ) {
655 + if ( 0 === $depth ) {
656 + $start = $match[1];
657 + }
658 + ++$depth;
659 + } elseif ( $depth > 0 ) {
660 + --$depth;
661 + if ( 0 === $depth ) {
662 + $ranges[] = array( $start, $match[1] );
663 + }
664 + }
665 + }
666 + if ( $depth > 0 ) {
667 + $ranges[] = array( $start, strlen( $html ) );
668 + }
669 + }
670 + return $ranges;
671 + }
672 +
673 + /** Does a byte offset fall inside any of the given [start, end] ranges? */
674 + private static function offset_in_ranges( int $offset, array $ranges ): bool {
675 + foreach ( $ranges as $range ) {
676 + if ( $offset > $range[0] && $offset < $range[1] ) {
677 + return true;
678 + }
679 + }
680 + return false;
681 + }
682 +
683 + /**
334 684 * Score for an image whose size we can't read at all.
335 685 *
336 686 * Deliberately non-zero: an unmeasurable image must still beat nothing and
337 687 * still be preloadable on a page where no image declares its size. But it
@@ -492,13 +842,21 @@
492 842 */
493 843 private const NON_HERO_MARKERS = array( 'logo', 'icon', 'avatar', 'gravatar', 'spinner', 'emoji', 'site-icon', 'custom-logo' );
494 844
495 845 /**
846 + * Below this declared area (px²) an image is a badge/thumb/divider, never
847 + * an LCP hero — 10 000 is a 100×100 square, or a 500×20 strip. Applied
848 + * only when BOTH dimensions are readable. (FBS-84576)
849 + */
850 + private const MIN_LCP_AREA = 10000;
851 +
852 + /**
496 853 * Is this <img> too small / too chrome-like to be the LCP hero? True when
497 854 * either (a) it carries a logo/icon/avatar marker, (b) an explicit
498 - * `data-no-lcp` opt-out, or (c) BOTH width and height are present and both
499 - * are ≤ the threshold. Missing dimensions are NOT guessed — an image whose
500 - * size we can't read still competes. (FBS-83553 H1 "logo before hero".)
855 + * `data-no-lcp` opt-out, or (c) BOTH width and height are present and
856 + * both are ≤ the dimension threshold, or their area is under
857 + * MIN_LCP_AREA. Missing dimensions are NOT guessed — an image whose size
858 + * we can't read still competes. (FBS-83553 H1 "logo before hero".)
501 859 */
502 860 private static function looks_too_small( string $tag ): bool {
503 861 if ( false !== stripos( $tag, 'data-no-lcp' ) ) {
504 862 return true;
@@ -514,8 +872,11 @@
514 872 $w = self::attr( $tag, 'width' );
515 873 $h = self::attr( $tag, 'height' );
516 874 if ( '' === $w || '' === $h || ! is_numeric( $w ) || ! is_numeric( $h ) ) {
517 875 return false; // unknown size — don't guess; let it compete.
876 + }
877 + if ( (int) $w * (int) $h < self::MIN_LCP_AREA ) {
878 + return true;
518 879 }
519 880 return (int) $w <= self::MIN_LCP_DIMENSION && (int) $h <= self::MIN_LCP_DIMENSION;
520 881 }
521 882