| @@ -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 |
| @@ -247,15 +247,57 @@ | ||
| 247 | 247 | * |
| 248 | 248 | * @param string $html Page HTML. |
| 249 | 249 | * @param int $count How many top images to preload. |
| 250 | 250 | * @param string[] $exclusions Substring patterns that exempt an <img>. |
| 251 | + * @param string $page_url The page being served, for the candidate seam. | |
| 251 | 252 | * @return array{0:string,1:string} [rewritten html, preload markup] |
| 252 | 253 | */ |
| 253 | - 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 { | |
| 254 | 255 | if ( $count < 1 ) { |
| 255 | 256 | return array( $html, '' ); |
| 256 | 257 | } |
| 257 | 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 | + | |
| 258 | 300 | $preload = ''; |
| 259 | 301 | |
| 260 | 302 | // Snapshot of already-present preload markup, for idempotency: a second |
| 261 | 303 | // pass (e.g. cache-off ob_start over an already-processed body) must not |
| @@ -415,9 +457,9 @@ | ||
| 415 | 457 | '#rel=["\']preload["\'][^>]*as=["\']image["\'][^>]*' . preg_quote( $w['src'], '#' ) . '#i', |
| 416 | 458 | $existing |
| 417 | 459 | ); |
| 418 | 460 | if ( ! $already ) { |
| 419 | - $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' ); | |
| 420 | 462 | } |
| 421 | 463 | // Only <img> winners are promoted in PASS 2 — there is no |
| 422 | 464 | // fetchpriority/loading attribute to fix on a background element, |
| 423 | 465 | // and its `order` is offset past every <img> index precisely so it |
| @@ -1106,9 +1148,9 @@ | ||
| 1106 | 1148 | * resource goes un-preloaded). By filtering the URL, a webp/avif layer can |
| 1107 | 1149 | * redirect the preload to the format it will actually serve, WITHOUT Free |
| 1108 | 1150 | * knowing that layer exists. (FBS-83553 H3) |
| 1109 | 1151 | */ |
| 1110 | - 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 { | |
| 1111 | 1153 | // Resolve the `type` from the ORIGINAL image URL (before rewriting), so a |
| 1112 | 1154 | // negotiating layer can key off the source .jpg/.png — after rewriting, |
| 1113 | 1155 | // the URL is already a .webp and the derivation would no-op. |
| 1114 | 1156 | $original = $src; |
| @@ -1119,20 +1161,28 @@ | ||
| 1119 | 1161 | * even though the markup is baked into a shared cache file. |
| 1120 | 1162 | * |
| 1121 | 1163 | * @param string $type Defaults to '' (no type attribute). |
| 1122 | 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. | |
| 1123 | 1169 | */ |
| 1124 | - $type = (string) apply_filters( 'xspeed_lcp_preload_type', '', $original ); | |
| 1170 | + $type = (string) apply_filters( 'xspeed_lcp_preload_type', '', $original, $kind ); | |
| 1125 | 1171 | /** |
| 1126 | 1172 | * Filter the LCP preload href. Return a modern-format sibling (webp/avif) |
| 1127 | 1173 | * when one will actually be served for this image. |
| 1128 | 1174 | * |
| 1129 | - * @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. | |
| 1130 | 1177 | */ |
| 1131 | - $src = (string) apply_filters( 'xspeed_lcp_preload_url', $src ); | |
| 1178 | + $src = (string) apply_filters( 'xspeed_lcp_preload_url', $src, $kind ); | |
| 1132 | 1179 | if ( '' !== $srcset ) { |
| 1133 | - /** @param string $srcset The original srcset chosen for preload. */ | |
| 1134 | - $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 ); | |
| 1135 | 1185 | } |
| 1136 | 1186 | |
| 1137 | 1187 | $attrs = sprintf( 'href="%s"', esc_url( $src ) ); |
| 1138 | 1188 | |
| @@ -1148,8 +1198,12 @@ | ||
| 1148 | 1198 | if ( '' !== $type ) { |
| 1149 | 1199 | $attrs .= sprintf( ' type="%s"', esc_attr( $type ) ); |
| 1150 | 1200 | } |
| 1151 | 1201 | |
| 1202 | + if ( '' !== $media ) { | |
| 1203 | + $attrs .= sprintf( ' media="%s"', esc_attr( $media ) ); | |
| 1204 | + } | |
| 1205 | + | |
| 1152 | 1206 | return sprintf( '<link rel="preload" as="image" %s fetchpriority="high">' . "\n", $attrs ); |
| 1153 | 1207 | } |
| 1154 | 1208 | |
| 1155 | 1209 | /** |
| @@ -1254,9 +1308,226 @@ | ||
| 1254 | 1308 | } |
| 1255 | 1309 | return (int) $w <= self::MIN_LCP_DIMENSION && (int) $h <= self::MIN_LCP_DIMENSION; |
| 1256 | 1310 | } |
| 1257 | 1311 | |
| 1312 | + /** Most candidates one answer may carry (one per device class). */ | |
| 1313 | + private const MAX_SUPPLIED_CANDIDATES = 3; | |
| 1314 | + | |
| 1258 | 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 `&` 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: `&` 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 | + /** | |
| 1259 | 1530 | * Promote an <img> to the LCP element: force fetchpriority="high" and |
| 1260 | 1531 | * strip any loading="lazy" so the browser loads it immediately. Both are |
| 1261 | 1532 | * idempotent. `loading="lazy"` is REMOVED rather than flipped to "eager" |
| 1262 | 1533 | * because eager is the default; a bare tag with fetchpriority="high" is |
| @@ -1287,8 +1558,16 @@ | ||
| 1287 | 1558 | * before the first stylesheet so the preloads are discovered before the |
| 1288 | 1559 | * render-blocking CSS. Falls back to after <head>, then prepend. |
| 1289 | 1560 | */ |
| 1290 | 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 | + } | |
| 1291 | 1570 | // Before the first <link rel="stylesheet"> if there is one. |
| 1292 | 1571 | if ( preg_match( '#<link\b[^>]*rel=["\']stylesheet["\'][^>]*>#i', $html, $m, PREG_OFFSET_CAPTURE ) ) { |
| 1293 | 1572 | $pos = $m[0][1]; |
| 1294 | 1573 | return substr( $html, 0, $pos ) . $hints . substr( $html, $pos ); |
| @@ -1299,6 +1578,147 @@ | ||
| 1299 | 1578 | return substr( $html, 0, $pos ) . "\n" . $hints . substr( $html, $pos ); |
| 1300 | 1579 | } |
| 1301 | 1580 | // No head at all — prepend (degenerate documents). |
| 1302 | 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; | |
| 1303 | 1723 | } |
| 1304 | 1724 | } |