| @@ -138,12 +138,34 @@ | ||
| 138 | 138 | } |
| 139 | 139 | if ( self::is_excluded_script( (string) $handle, (string) $src ) ) { |
| 140 | 140 | return $tag; |
| 141 | 141 | } |
| 142 | + // Inline code elsewhere on the page reads this handle (or something | |
| 143 | + // it depends on). Inline blocks never defer, so deferring this one | |
| 144 | + // would run the consumer first. Defer only — delay is an opt-in | |
| 145 | + // target list, where the user has named the script deliberately. | |
| 146 | + if ( isset( self::inline_bound_handles()[ (string) $handle ] ) ) { | |
| 147 | + return $tag; | |
| 148 | + } | |
| 149 | + // NB: is_protected_from_bundling() is the same two rules in one call | |
| 150 | + // for the combiner; the split here is deliberate, since the | |
| 151 | + // exclusion check above already ran and short-circuits earlier. | |
| 142 | 152 | if ( false !== stripos( $tag, ' defer' ) || false !== stripos( $tag, ' async' ) ) { |
| 143 | 153 | return $tag; |
| 144 | 154 | } |
| 145 | - return (string) preg_replace( '#<script\b#i', '<script defer="defer"', $tag, 1 ); | |
| 155 | + // Target the <script> that actually carries a src, NOT simply the | |
| 156 | + // first one in the string. WP_Scripts::do_item() hands this filter | |
| 157 | + // the CONCATENATION of before_inline + external + after_inline, so | |
| 158 | + // for any handle carrying a `before` inline script the first | |
| 159 | + // `<script` is the inline block. Deferring that is a no-op (the HTML | |
| 160 | + // spec ignores defer on inline scripts) AND leaves the external | |
| 161 | + // script undeferred while its dependencies get deferred — which | |
| 162 | + // inverts WordPress's guaranteed execution order and throws in any | |
| 163 | + // dependent that touches a global its dependency defines. (#234) | |
| 164 | + // | |
| 165 | + // The lookahead scans only within the tag (`[^>]*`) for ` src=`, so | |
| 166 | + // an inline `<script id="…-js-before">` can never match. | |
| 167 | + return (string) preg_replace( '#<script\b(?=[^>]*\ssrc\s*=)#i', '<script defer="defer"', $tag, 1 ); | |
| 146 | 168 | } |
| 147 | 169 | |
| 148 | 170 | /** |
| 149 | 171 | * Filter: `script_loader_tag` — rewrite src= to data-xs-src= so the |
| @@ -168,25 +190,71 @@ | ||
| 168 | 190 | } |
| 169 | 191 | if ( ! self::is_delay_target( (string) $handle, (string) $src ) ) { |
| 170 | 192 | return $tag; |
| 171 | 193 | } |
| 194 | + // Inline code elsewhere on the page reads this handle (or something | |
| 195 | + // it depends on) — same registry walk defer uses. Delaying it runs | |
| 196 | + // the consumer at parse time against a global that arrives on first | |
| 197 | + // interaction: `wp_add_inline_script( 'jquery-ui-core', | |
| 198 | + // 'jQuery.uiBackCompat…', 'before' )` throws "jQuery is not defined" | |
| 199 | + // the moment jquery-core is delayed. A handle the user NAMED in | |
| 200 | + // delay_js_targets is still delayed — an explicit entry is the user | |
| 201 | + // saying they know the inline consumer is safe to break or absent. | |
| 202 | + if ( isset( self::inline_bound_handles()[ (string) $handle ] ) | |
| 203 | + && ! self::is_user_named_target( (string) $handle, (string) $src ) ) { | |
| 204 | + return $tag; | |
| 205 | + } | |
| 206 | + // A non-executable type means this tag is data, or is being held by | |
| 207 | + // somebody else on purpose. The buffer pass has always checked this; | |
| 208 | + // the enqueue path did not, so a consent-blocked or JSON-carrying | |
| 209 | + // handle could still be rewritten here. (#274) | |
| 210 | + if ( in_array( self::extract_type( $tag ), self::NON_EXECUTABLE_TYPES, true ) ) { | |
| 211 | + return $tag; | |
| 212 | + } | |
| 172 | 213 | // src= variant: swap src → data-xs-src and add data-xs-delay marker. |
| 173 | 214 | if ( '' !== (string) $src ) { |
| 215 | + // Anchor on the opening <script …> tag that carries the src. | |
| 216 | + // Matching a bare `src=` across the whole string would rewrite | |
| 217 | + // the first occurrence anywhere — including inside a `before` | |
| 218 | + // inline block, where JS like `el.src = "…"` becomes the | |
| 219 | + // syntax error `el.data-xs-src="…" data-xs-delay="1"` and the | |
| 220 | + // real external script is left undelayed. $tag is the | |
| 221 | + // concatenation of before_inline + external + after_inline, | |
| 222 | + // so that is a routine shape, not a corner case. (#234) | |
| 223 | + // `(?<![-\w])` where `\b` used to be. A hyphen is a non-word | |
| 224 | + // character, so `\bsrc=` also matches the TAIL of any | |
| 225 | + // `data-…-src=` attribute — and consent managers and other | |
| 226 | + // optimizers park a blocked script's real URL in exactly that | |
| 227 | + // shape. Complianz's `data-cmplz-src` became | |
| 228 | + // `data-cmplz-data-xs-src`, so after the visitor clicked Accept | |
| 229 | + // the plugin looked for an attribute that no longer existed and | |
| 230 | + // the script never loaded: analytics and pixels silently dead, | |
| 231 | + // no console error, nothing in the UI. Same class of bug as the | |
| 232 | + // image-dimension resolver in #328. (#273) | |
| 174 | 233 | return (string) preg_replace( |
| 175 | - '#\bsrc\s*=\s*(["\'][^"\']*["\'])#i', | |
| 176 | - 'data-xs-src=$1 data-xs-delay="1"', | |
| 234 | + '#(<script\b[^>]*?)(?<![-\w])src\s*=\s*(["\'][^"\']*["\'])#i', | |
| 235 | + '$1data-xs-src=$2 data-xs-delay="1"', | |
| 177 | 236 | $tag, |
| 178 | 237 | 1 |
| 179 | 238 | ); |
| 180 | 239 | } |
| 181 | - // Inline script: change type to text/plain so the browser | |
| 182 | - // doesn't execute, mark for bootstrap rewriter. | |
| 183 | - return (string) preg_replace( | |
| 240 | + // Inline script: change type to text/xspeed-delayed so the browser | |
| 241 | + // doesn't execute, mark for bootstrap rewriter. Any existing type | |
| 242 | + // is REPLACED, not appended-after: HTML keeps an attribute's first | |
| 243 | + // occurrence, so a snippet carrying its own `type="text/javascript"` | |
| 244 | + // would win over a marker appended behind it and keep executing. | |
| 245 | + // A non-default original type is stashed in data-xs-type so the | |
| 246 | + // bootstrap can restore it on replay (#274 — type is what a script | |
| 247 | + // IS; a parked `type="module"` must come back as a module). | |
| 248 | + $tag = (string) preg_replace_callback( | |
| 184 | 249 | '#<script\b([^>]*)>#i', |
| 185 | - '<script$1 type="text/xspeed-delayed" data-xs-delay="1">', | |
| 250 | + static function ( array $m ): string { | |
| 251 | + return '<script' . self::park_type_attrs( $m[1] ) . '>'; | |
| 252 | + }, | |
| 186 | 253 | $tag, |
| 187 | 254 | 1 |
| 188 | 255 | ); |
| 256 | + return $tag; | |
| 189 | 257 | } |
| 190 | 258 | |
| 191 | 259 | /** |
| 192 | 260 | * Script types the buffer pass must never touch. `<script>` carries |
| @@ -202,11 +270,82 @@ | ||
| 202 | 270 | 'speculationrules', |
| 203 | 271 | 'text/template', |
| 204 | 272 | 'text/x-template', |
| 205 | 273 | 'text/xspeed-delayed', |
| 274 | + // A consent manager parks a blocked third-party script here and | |
| 275 | + // swaps the type back only once the visitor has agreed. Whatever we | |
| 276 | + // do to such a tag we do on behalf of a decision the visitor has not | |
| 277 | + // made yet, so the only correct move is to leave it alone. (#274) | |
| 278 | + 'text/plain', | |
| 206 | 279 | ); |
| 207 | 280 | |
| 208 | 281 | /** |
| 282 | + * The `type` attribute, quoted OR unquoted, anchored to attribute | |
| 283 | + * position — a required leading whitespace, never a bare `\b`. | |
| 284 | + * | |
| 285 | + * The anchoring matters twice over. `\btype` also matches the tail of | |
| 286 | + * any hyphenated `data-…-type` attribute (a `-` is a non-word char, so | |
| 287 | + * the boundary sits inside the name — the same #273 class as `src`), | |
| 288 | + * and it matches a `type=` sitting INSIDE another attribute's value | |
| 289 | + * (`onload="this.type='done'"`). Requiring whitespace before the name | |
| 290 | + * rules both out: attributes are whitespace-separated, while `.type` | |
| 291 | + * and `-type` never are. The unquoted branch exists because | |
| 292 | + * `type=text/javascript` is valid HTML: a quoted-only pattern left it | |
| 293 | + * standing, the parking type appended after it lost the | |
| 294 | + * first-occurrence race, and the snippet executed immediately AND | |
| 295 | + * replayed on interaction — every vendor event fired twice. | |
| 296 | + */ | |
| 297 | + private const TYPE_ATTR_RE = '#\stype\s*=\s*(?:(["\'])(.*?)\1|([^\s>]+))#is'; | |
| 298 | + | |
| 299 | + /** | |
| 300 | + * `type` values a parked tag need not remember: the replay default is | |
| 301 | + * already JavaScript, so stashing these would only fatten the markup. | |
| 302 | + */ | |
| 303 | + private const DEFAULT_JS_TYPES = array( | |
| 304 | + 'text/javascript', | |
| 305 | + 'application/javascript', | |
| 306 | + ); | |
| 307 | + | |
| 308 | + /** | |
| 309 | + * Read a tag's `type` attribute value, lowercased and trimmed. | |
| 310 | + * | |
| 311 | + * @param string $haystack Full tag or its attribute string. | |
| 312 | + * @return string '' when no type attribute is present. | |
| 313 | + */ | |
| 314 | + private static function extract_type( string $haystack ): string { | |
| 315 | + if ( ! preg_match( self::TYPE_ATTR_RE, $haystack, $m ) ) { | |
| 316 | + return ''; | |
| 317 | + } | |
| 318 | + $value = ( isset( $m[3] ) && '' !== $m[3] ) ? $m[3] : $m[2]; | |
| 319 | + return strtolower( trim( $value ) ); | |
| 320 | + } | |
| 321 | + | |
| 322 | + /** | |
| 323 | + * Rewrite an inline tag's attribute string for parking: strip its own | |
| 324 | + * `type`, stash a non-default one in `data-xs-type` (the bootstrap | |
| 325 | + * restores it on replay, so a parked `type="module"` comes back as a | |
| 326 | + * module rather than a classic script — #274), and append the parking | |
| 327 | + * marker pair. | |
| 328 | + * | |
| 329 | + * @param string $attrs Raw attribute string (everything between | |
| 330 | + * `<script` and `>`). | |
| 331 | + */ | |
| 332 | + private static function park_type_attrs( string $attrs ): string { | |
| 333 | + $orig = self::extract_type( $attrs ); | |
| 334 | + $attrs = (string) preg_replace( self::TYPE_ATTR_RE, '', $attrs ); | |
| 335 | + $stash = ''; | |
| 336 | + if ( '' !== $orig && ! in_array( $orig, self::DEFAULT_JS_TYPES, true ) ) { | |
| 337 | + // MIME-ish charset only — a type value is never markup, and this | |
| 338 | + // string is re-emitted inside a double-quoted attribute. | |
| 339 | + $orig = (string) preg_replace( '#[^a-z0-9/+.\-]#', '', $orig ); | |
| 340 | + if ( '' !== $orig ) { | |
| 341 | + $stash = ' data-xs-type="' . $orig . '"'; | |
| 342 | + } | |
| 343 | + } | |
| 344 | + return $attrs . $stash . ' type="text/xspeed-delayed" data-xs-delay="1"'; | |
| 345 | + } | |
| 346 | + | |
| 347 | + /** | |
| 209 | 348 | * URL fragments that must keep a live src no matter what. The enqueue |
| 210 | 349 | * path guards these by handle (ALWAYS_EXCLUDED_HANDLES), but a buffer |
| 211 | 350 | * pass only ever sees a URL, so the same protection is re-expressed |
| 212 | 351 | * here. Without this the admin bundle could be delayed on a frontend |
| @@ -261,19 +400,21 @@ | ||
| 261 | 400 | |
| 262 | 401 | // No src → inline code. The enqueue path owns those; a |
| 263 | 402 | // buffer rewrite here would have to reason about execution |
| 264 | 403 | // order it cannot see. |
| 265 | - if ( ! preg_match( '#\bsrc\s*=\s*(["\'])(.*?)\1#is', $tag, $src_m ) ) { | |
| 404 | + // `(?<![-\w])` not `\b` — see the note on the enqueue-path | |
| 405 | + // rewrite above. With `\b`, a tag whose ONLY url lives in | |
| 406 | + // `data-cmplz-src` (a consent-blocked script, no real src at | |
| 407 | + // all) read as an external script here, and the rewrite | |
| 408 | + // below then mangled that attribute. (#273) | |
| 409 | + if ( ! preg_match( '#(?<![-\w])src\s*=\s*(["\'])(.*?)\1#is', $tag, $src_m ) ) { | |
| 266 | 410 | return $tag; |
| 267 | 411 | } |
| 268 | 412 | $src = $src_m[2]; |
| 269 | 413 | |
| 270 | 414 | // Data, not code. |
| 271 | - if ( preg_match( '#\btype\s*=\s*(["\'])(.*?)\1#is', $tag, $type_m ) ) { | |
| 272 | - $type = strtolower( trim( $type_m[2] ) ); | |
| 273 | - if ( in_array( $type, self::NON_EXECUTABLE_TYPES, true ) ) { | |
| 274 | - return $tag; | |
| 275 | - } | |
| 415 | + if ( in_array( self::extract_type( $tag ), self::NON_EXECUTABLE_TYPES, true ) ) { | |
| 416 | + return $tag; | |
| 276 | 417 | } |
| 277 | 418 | |
| 278 | 419 | foreach ( self::ALWAYS_EXCLUDED_SRC as $needle ) { |
| 279 | 420 | if ( false !== stripos( $src, $needle ) ) { |
| @@ -280,18 +421,53 @@ | ||
| 280 | 421 | return $tag; |
| 281 | 422 | } |
| 282 | 423 | } |
| 283 | 424 | |
| 284 | - // Buffer-pass tags have no handle — match on URL only. | |
| 285 | - if ( self::is_excluded_script( '', $src ) ) { | |
| 425 | + // Recover the handle from the tag's id before deciding. | |
| 426 | + // | |
| 427 | + // This pass used to pass '' as the handle, on the reasoning | |
| 428 | + // that a tag reaching the buffer was never enqueued and so has | |
| 429 | + // none. That holds for the third-party snippets this pass | |
| 430 | + // exists for — but NOT for enqueued scripts, which also travel | |
| 431 | + // through here, and which WordPress prints with | |
| 432 | + // `id="<handle>-js"`. Passing '' meant every handle-based | |
| 433 | + // exclusion was silently inert at this layer: the user writes | |
| 434 | + // `jquery-core`, the enqueue path honours it, and then the | |
| 435 | + // buffer pass — which only ever compared URLs — delayed the | |
| 436 | + // very script the list was protecting. | |
| 437 | + // | |
| 438 | + // That is how a site with jquery-core AND jquery-migrate | |
| 439 | + // excluded still shipped jQuery delayed while migrate loaded | |
| 440 | + // normally, and every inline `jQuery(...)` on the page threw | |
| 441 | + // "jQuery is not defined". The two behaved differently for no | |
| 442 | + // reason a user could see, which is what made it look like a | |
| 443 | + // matching quirk rather than a whole layer ignoring the list. | |
| 444 | + $tag_handle = ''; | |
| 445 | + if ( preg_match( '#\sid\s*=\s*(["\'])(.*?)\1#i', $tag, $id_m ) ) { | |
| 446 | + // WP appends `-js`; anything else is somebody's own id and | |
| 447 | + // is still worth matching literally. | |
| 448 | + $tag_handle = (string) preg_replace( '/-js$/', '', $id_m[2] ); | |
| 449 | + } | |
| 450 | + | |
| 451 | + if ( self::is_excluded_script( $tag_handle, $src ) ) { | |
| 286 | 452 | return $tag; |
| 287 | 453 | } |
| 288 | - if ( ! self::is_delay_target( '', $src ) ) { | |
| 454 | + if ( ! self::is_delay_target( $tag_handle, $src ) ) { | |
| 289 | 455 | return $tag; |
| 290 | 456 | } |
| 457 | + // Mirror of the enqueue-path guard: a handle that inline code | |
| 458 | + // reads stays eager unless the user named it. wp_scripts() | |
| 459 | + // is still populated at xspeed_cache_final_html time on a | |
| 460 | + // MISS, so the registry walk is consultable here too; an | |
| 461 | + // unrecoverable handle ('') simply never matches the set. | |
| 462 | + if ( '' !== $tag_handle | |
| 463 | + && isset( self::inline_bound_handles()[ $tag_handle ] ) | |
| 464 | + && ! self::is_user_named_target( $tag_handle, $src ) ) { | |
| 465 | + return $tag; | |
| 466 | + } | |
| 291 | 467 | |
| 292 | 468 | return (string) preg_replace( |
| 293 | - '#\bsrc\s*=\s*(["\'][^"\']*["\'])#i', | |
| 469 | + '#(?<![-\w])src\s*=\s*(["\'][^"\']*["\'])#i', | |
| 294 | 470 | 'data-xs-src=$1 data-xs-delay="1"', |
| 295 | 471 | $tag, |
| 296 | 472 | 1 |
| 297 | 473 | ); |
| @@ -300,8 +476,114 @@ | ||
| 300 | 476 | ); |
| 301 | 477 | } |
| 302 | 478 | |
| 303 | 479 | /** |
| 480 | + * Delay inline vendor snippets that reference a known third-party host. | |
| 481 | + * | |
| 482 | + * The pass above rewrites `src` and deliberately leaves inline code | |
| 483 | + * alone — but the OFFICIAL install for Clarity, GA, GTM and the Meta | |
| 484 | + * pixel is an inline loader (`(function(c,l,a,r,i,t,y){…t.src=…})`) | |
| 485 | + * with no `src` attribute at all. That snippet executes on every page | |
| 486 | + * load, fetches the vendor bundle inside the measurement window, and | |
| 487 | + * puts the one host whose Cache-Control the site cannot set straight | |
| 488 | + * into the cache-policy and TBT audits. Delaying the enqueue path and | |
| 489 | + * the raw-src path while this runs untouched is delaying everything | |
| 490 | + * except the tag the feature exists for. | |
| 491 | + * | |
| 492 | + * The judgment call is the same one KNOWN_THIRD_PARTY_SRC already | |
| 493 | + * makes: an inline body that names one of those hosts is that vendor's | |
| 494 | + * loader or its config — never something first-party code holds a | |
| 495 | + * synchronous reference to. The body is the haystack for the user's | |
| 496 | + * exclusion and target lists too, so the same fragment that protects a | |
| 497 | + * `src` tag protects its inline install. | |
| 498 | + * | |
| 499 | + * `document.write` bodies are skipped outright: replayed after the | |
| 500 | + * parser has closed the document, a delayed write would replace the | |
| 501 | + * page rather than add to it. | |
| 502 | + * | |
| 503 | + * @param string $html Complete page HTML. | |
| 504 | + */ | |
| 505 | + public static function delay_inline_snippets( $html ): string { | |
| 506 | + if ( ! is_string( $html ) || '' === $html ) { | |
| 507 | + return (string) $html; | |
| 508 | + } | |
| 509 | + if ( self::skip_in_non_frontend_context() ) { | |
| 510 | + return $html; | |
| 511 | + } | |
| 512 | + $opts = self::opts(); | |
| 513 | + if ( empty( $opts['delay_js'] ) ) { | |
| 514 | + return $html; | |
| 515 | + } | |
| 516 | + | |
| 517 | + $out = preg_replace_callback( | |
| 518 | + '#<script\b([^>]*)>(.*?)</script>#is', | |
| 519 | + static function ( array $m ): string { | |
| 520 | + list( $whole, $attrs, $body ) = $m; | |
| 521 | + | |
| 522 | + if ( '' === trim( $body ) ) { | |
| 523 | + return $whole; | |
| 524 | + } | |
| 525 | + | |
| 526 | + // Our own replay bootstrap. Its body quotes the delay | |
| 527 | + // machinery's own strings, so a pathological user target | |
| 528 | + // fragment could match it — and a parked bootstrap means | |
| 529 | + // nothing on the page ever replays. | |
| 530 | + if ( false !== stripos( $attrs, 'xspeed-delay-bootstrap' ) ) { | |
| 531 | + return $whole; | |
| 532 | + } | |
| 533 | + | |
| 534 | + // Already marked, or a real src= — the src passes own those. | |
| 535 | + // `(?<![-\w])` for the same reason as above: `data-cmplz-src` | |
| 536 | + // must not read as a src. (#273) | |
| 537 | + if ( false !== stripos( $attrs, 'data-xs-delay' ) || false !== stripos( $attrs, 'data-xs-src' ) ) { | |
| 538 | + return $whole; | |
| 539 | + } | |
| 540 | + if ( preg_match( '#(?<![-\w])src\s*=\s*(["\']).*?\1#is', $attrs ) ) { | |
| 541 | + return $whole; | |
| 542 | + } | |
| 543 | + | |
| 544 | + // Data, a module map, or a consent manager's parked tag. | |
| 545 | + if ( in_array( self::extract_type( $attrs ), self::NON_EXECUTABLE_TYPES, true ) ) { | |
| 546 | + return $whole; | |
| 547 | + } | |
| 548 | + | |
| 549 | + // A delayed document.write replays after the document has | |
| 550 | + // closed and replaces the page. Never delay one. | |
| 551 | + if ( false !== stripos( $body, 'document.write' ) ) { | |
| 552 | + return $whole; | |
| 553 | + } | |
| 554 | + | |
| 555 | + // The body stands in for the URL in the lists the src passes | |
| 556 | + // consult — but NOT via is_delay_target(), whose empty-list | |
| 557 | + // default is "delay everything". That default is right for a | |
| 558 | + // tag with a URL and catastrophic here: it would park every | |
| 559 | + // inline script on the page. Inline code is delayed only on a | |
| 560 | + // positive identification — the body names a known vendor | |
| 561 | + // host, or a fragment the user targeted — and the exclusion | |
| 562 | + // list still wins first. | |
| 563 | + if ( self::is_excluded_script( '', $body ) ) { | |
| 564 | + return $whole; | |
| 565 | + } | |
| 566 | + if ( ! self::matches_known_third_party( $body ) && ! self::matches_user_targets( $body ) ) { | |
| 567 | + return $whole; | |
| 568 | + } | |
| 569 | + | |
| 570 | + // Replace — not append — any existing type. Attributes keep | |
| 571 | + // their FIRST occurrence in HTML, so appending the parking | |
| 572 | + // type after the snippet's own `type="text/javascript"` | |
| 573 | + // would leave the original executable. A non-default type is | |
| 574 | + // stashed in data-xs-type for the bootstrap to restore. | |
| 575 | + return '<script' . self::park_type_attrs( $attrs ) . '>' . $body . '</script>'; | |
| 576 | + }, | |
| 577 | + $html | |
| 578 | + ); | |
| 579 | + // A PCRE failure (backtrack limit on a huge inline body) returns | |
| 580 | + // null — and casting that to '' would serve AND cache a blank page. | |
| 581 | + // The unrewritten original is always the safe fallback. | |
| 582 | + return null === $out ? $html : $out; | |
| 583 | + } | |
| 584 | + | |
| 585 | + /** | |
| 304 | 586 | * Inline bootstrap that flips delayed scripts on the first user |
| 305 | 587 | * interaction. Printed once on wp_footer priority 1000. |
| 306 | 588 | */ |
| 307 | 589 | public static function print_delay_bootstrap(): void { |
| @@ -334,11 +616,41 @@ | ||
| 334 | 616 | events.forEach(function(e){window.removeEventListener(e,load,{passive:true,capture:true});}); |
| 335 | 617 | var delayed=document.querySelectorAll('script[data-xs-delay]'); |
| 336 | 618 | delayed.forEach(function(s){ |
| 337 | 619 | var n=document.createElement('script'); |
| 620 | + // A dynamically-created script is async by default, so replayed | |
| 621 | + // EXTERNALS would race each other; async=false restores document | |
| 622 | + // order among the externals. Narrower guarantee, stated plainly: | |
| 623 | + // a replayed INLINE script still executes synchronously at its | |
| 624 | + // replaceChild, i.e. possibly before an earlier external has | |
| 625 | + // finished LOADING — so an inline consumer of a delayed external | |
| 626 | + // is only safe when both were delayed by explicit user targeting | |
| 627 | + // (the inline-bound guard keeps the implicit case eager). | |
| 628 | + n.async=false; | |
| 629 | + // Nonce hiding: a connected element's nonce CONTENT attribute reads | |
| 630 | + // as "", so copying it via the attribute loop would hand the clone | |
| 631 | + // an empty nonce and a nonce-based CSP would block the replay. The | |
| 632 | + // IDL property still carries the real value. | |
| 633 | + if(s.nonce){n.nonce=s.nonce;} | |
| 338 | 634 | Array.prototype.slice.call(s.attributes).forEach(function(a){ |
| 339 | 635 | if(a.name==='data-xs-src'){n.setAttribute('src',a.value);return;} |
| 340 | - if(a.name==='data-xs-delay'||a.name==='type')return; | |
| 636 | + if(a.name==='data-xs-delay')return; | |
| 637 | + if(a.name==='nonce')return; | |
| 638 | + // A parked inline tag's ORIGINAL type (module, mostly) rides in | |
| 639 | + // data-xs-type — restore it, or the replay runs a module as a | |
| 640 | + // classic script and its imports throw. (#274) | |
| 641 | + if(a.name==='data-xs-type'){n.setAttribute('type',a.value);return;} | |
| 642 | + // `type` is what a script IS, not decoration, so it is carried over | |
| 643 | + // — with ONE exception: our own inline parking marker, which exists | |
| 644 | + // only to stop the browser executing the original and must not be | |
| 645 | + // copied onto the replacement. Dropping type wholesale broke two | |
| 646 | + // things: `type="module"` became a classic script (core's Script | |
| 647 | + // Modules — Navigation, lightbox, Query Loop — threw "Cannot use | |
| 648 | + // import statement outside a module" on the default theme), and | |
| 649 | + // `type="text/plain"`, which is precisely how a consent manager | |
| 650 | + // parks a blocked third-party script, became executable again. The | |
| 651 | + // second is a privacy failure, not a broken feature. (#274) | |
| 652 | + if(a.name==='type'&&a.value==='text/xspeed-delayed')return; | |
| 341 | 653 | n.setAttribute(a.name,a.value); |
| 342 | 654 | }); |
| 343 | 655 | if(!s.hasAttribute('data-xs-src')){n.text=s.text;} |
| 344 | 656 | s.parentNode.replaceChild(n,s); |
| @@ -374,12 +686,96 @@ | ||
| 374 | 686 | // want to fight with explicit author intent. |
| 375 | 687 | if ( false === stripos( $tag, 'rel=\'stylesheet\'' ) && false === stripos( $tag, 'rel="stylesheet"' ) ) { |
| 376 | 688 | return $tag; |
| 377 | 689 | } |
| 690 | + // The stylesheets that lay the page out stay render-blocking. | |
| 691 | + // | |
| 692 | + // This transform moves a sheet to AFTER first paint. That is the | |
| 693 | + // point of it — but a sheet the layout depends on is then missing | |
| 694 | + // from the only paint the visitor sees, and the page renders as | |
| 695 | + // unstyled HTML (bulleted nav, underlined links) until the swap | |
| 696 | + // runs. The pattern is only safe when something already styles the | |
| 697 | + // above-the-fold area, i.e. critical CSS — which Free does not | |
| 698 | + // generate. Deferring EVERY sheet on a site without it guarantees | |
| 699 | + // the flash rather than risking it: on the reported Kadence site | |
| 700 | + // all 17 stylesheets were deferred and none was render-blocking, | |
| 701 | + // so there was nothing left to paint the page with. (#269) | |
| 702 | + if ( self::is_layout_critical_style( $handle ) ) { | |
| 703 | + return $tag; | |
| 704 | + } | |
| 705 | + // A JS-measured layout on this page makes deferral unsafe for EVERY | |
| 706 | + // sheet, not just the theme's. | |
| 707 | + // | |
| 708 | + // Masonry, isotope, packery and the slider libraries lay elements out | |
| 709 | + // by MEASURING them and then writing absolute positions. Deferring the | |
| 710 | + // stylesheet that sizes those elements means the script measures them | |
| 711 | + // unstyled — zero or full-width — computes positions from those wrong | |
| 712 | + // numbers, and commits them. The CSS arriving a moment later cannot | |
| 713 | + // undo it: the script has already run and does not re-measure. The | |
| 714 | + // result is a permanently broken grid (items overlapping, or stranded | |
| 715 | + // with a large gap), which is worse than the flash this feature's | |
| 716 | + // other guard prevents, because it never resolves itself. | |
| 717 | + // | |
| 718 | + // This is checked per PAGE rather than per handle deliberately. The | |
| 719 | + // script that measures is rarely the one whose handle matches the | |
| 720 | + // sheet — Kadence's gallery is styled by | |
| 721 | + // `kadence-blocks-advancedgallery` but laid out by core's `masonry` — | |
| 722 | + // so pairing handles misses it. Whether a measuring library is present | |
| 723 | + // at all is the signal that generalises. (#269) | |
| 724 | + if ( self::page_has_js_measured_layout() ) { | |
| 725 | + return $tag; | |
| 726 | + } | |
| 378 | 727 | // Avoid double-wrapping. |
| 379 | 728 | if ( false !== stripos( $tag, 'data-xs-async' ) ) { |
| 380 | 729 | return $tag; |
| 381 | 730 | } |
| 731 | + // Someone else already made this sheet non-render-blocking. | |
| 732 | + // | |
| 733 | + // Plugins that ship their own async-CSS handling apply the same | |
| 734 | + // media="print" + onload swap we do, and they run on the SAME | |
| 735 | + // filter — SureCookie's consent banner does it at style_loader_tag | |
| 736 | + // priority 10, ours is priority 20, so its finished tag arrives | |
| 737 | + // here looking like a plain stylesheet with no marker of ours. | |
| 738 | + // | |
| 739 | + // Transforming it again breaks the sheet two ways: the media we'd | |
| 740 | + // capture as "the original to restore" is already `print`, so we | |
| 741 | + // emit onload="this.media='print'" — a swap to itself that never | |
| 742 | + // activates the stylesheet — and we append a SECOND onload | |
| 743 | + // attribute, of which the parser honours only the first (ours), | |
| 744 | + // discarding the plugin's correct this.media='all'. The banner | |
| 745 | + // then mounts unstyled, in both logged-in and logged-out states. | |
| 746 | + // | |
| 747 | + // An onload handler or a print media on a stylesheet link is only | |
| 748 | + // ever this pattern; a genuinely print-only sheet is already off | |
| 749 | + // the critical path and gains nothing from us. Either way the | |
| 750 | + // right move is to leave the tag alone — the same "don't fight | |
| 751 | + // explicit author intent" rule the rel= check above applies. (#216) | |
| 752 | + if ( preg_match( '#\bonload\s*=#i', $tag ) ) { | |
| 753 | + return $tag; | |
| 754 | + } | |
| 755 | + if ( preg_match( '#\bmedia\s*=\s*(["\'])\s*print\s*\1#i', $tag ) ) { | |
| 756 | + return $tag; | |
| 757 | + } | |
| 758 | + return self::async_link_markup( $tag ); | |
| 759 | + } | |
| 760 | + | |
| 761 | + /** | |
| 762 | + * The one place the async-CSS output shape lives: swap the link's media | |
| 763 | + * to `print`, restore the original media onload, record it in | |
| 764 | + * `data-xs-async`, and re-emit the untouched tag inside `<noscript>` for | |
| 765 | + * clients that never run the onload handler. | |
| 766 | + * | |
| 767 | + * Shared by the enqueue-path filter above and the raw-tag buffer pass | |
| 768 | + * below so the two can never drift — Pro's Critical CSS recognises this | |
| 769 | + * exact marker to avoid double-wrapping, and a second copy of the | |
| 770 | + * pattern is how that kind of contract quietly breaks. | |
| 771 | + * | |
| 772 | + * Callers own every skip decision (markers, onload, non-screen media); | |
| 773 | + * this helper only produces the markup. | |
| 774 | + * | |
| 775 | + * @param string $tag A `<link rel="stylesheet">` tag deemed safe to defer. | |
| 776 | + */ | |
| 777 | + private static function async_link_markup( string $tag ): string { | |
| 382 | 778 | $async = (string) preg_replace_callback( |
| 383 | 779 | '#\bmedia\s*=\s*(["\'])([^"\']*)\1#i', |
| 384 | 780 | static function ( $m ) { |
| 385 | 781 | $orig = $m[2]; |
| @@ -401,8 +797,284 @@ | ||
| 401 | 797 | return $async . '<noscript>' . $tag . '</noscript>'; |
| 402 | 798 | } |
| 403 | 799 | |
| 404 | 800 | /** |
| 801 | + * Stylesheet hosts that serve FONT CSS — small, render-blocking sheets of | |
| 802 | + * `@font-face` rules. The buffer pass below defers only these: a raw | |
| 803 | + * cross-origin `<link>` could carry anything, and blindly deferring an | |
| 804 | + * unknown vendor's layout CSS from the buffer would reintroduce the | |
| 805 | + * unstyled-flash failure async_style_tag()'s guards exist to prevent. | |
| 806 | + * Font CSS is the safe subset — text renders in a fallback face and swaps, | |
| 807 | + * which is exactly what `font-display: swap` does on purpose. | |
| 808 | + */ | |
| 809 | + private const FONT_CSS_HOSTS = array( | |
| 810 | + 'fonts.googleapis.com', | |
| 811 | + 'fonts.bunny.net', | |
| 812 | + 'use.typekit.net', | |
| 813 | + 'p.typekit.net', | |
| 814 | + 'fonts.cdnfonts.com', | |
| 815 | + ); | |
| 816 | + | |
| 817 | + /** | |
| 818 | + * The font-CSS host allowlist, filtered and normalised. | |
| 819 | + * | |
| 820 | + * @return string[] Lowercase hostnames. | |
| 821 | + */ | |
| 822 | + private static function font_css_hosts(): array { | |
| 823 | + /** | |
| 824 | + * Hosts whose stylesheet links the async-CSS buffer pass rewrites to | |
| 825 | + * the non-blocking print → onload pattern. Only font-CSS providers | |
| 826 | + * belong here: every listed host's sheets are safe to load late | |
| 827 | + * because they only add `@font-face` rules. | |
| 828 | + * | |
| 829 | + * @param string[] $hosts Hostnames (exact match, case-insensitive). | |
| 830 | + */ | |
| 831 | + $hosts = (array) apply_filters( 'xspeed_async_css_font_hosts', self::FONT_CSS_HOSTS ); | |
| 832 | + | |
| 833 | + return array_map( 'strtolower', array_map( 'strval', $hosts ) ); | |
| 834 | + } | |
| 835 | + | |
| 836 | + /** | |
| 837 | + * Media values that never apply to a screen paint. A sheet restricted to | |
| 838 | + * one of these is not render-blocking for screen, so deferring it saves | |
| 839 | + * nothing — and `print` in particular is either a genuine print sheet or | |
| 840 | + * somebody's finished async pattern, both of which must be left alone. | |
| 841 | + */ | |
| 842 | + private const NON_SCREEN_MEDIA = array( | |
| 843 | + 'print', | |
| 844 | + 'speech', | |
| 845 | + 'aural', | |
| 846 | + 'braille', | |
| 847 | + 'embossed', | |
| 848 | + 'handheld', | |
| 849 | + 'projection', | |
| 850 | + 'tty', | |
| 851 | + 'tv', | |
| 852 | + ); | |
| 853 | + | |
| 854 | + /** | |
| 855 | + * Filter: `xspeed_cache_final_html` — defer RAW font-CSS stylesheet links | |
| 856 | + * that never passed through wp_enqueue_style. | |
| 857 | + * | |
| 858 | + * `async_style_tag()` hooks `style_loader_tag`, so it only ever sees | |
| 859 | + * enqueued stylesheets. Themes and font plugins print Google Fonts (and | |
| 860 | + * Bunny, Typekit, CDNFonts) as literal | |
| 861 | + * `<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=…">` | |
| 862 | + * markup in the head — on the site that surfaced this, four such tags — | |
| 863 | + * and each one stays render-blocking with no plugin lever. Unused CSS | |
| 864 | + * skips cross-origin hrefs by design, so nothing else picks them up. | |
| 865 | + * | |
| 866 | + * Runs on the finished page buffer, so the rewrite is baked into the | |
| 867 | + * cached HTML and replays on every static hit. Deliberately narrow: only | |
| 868 | + * links whose host is on the font-CSS allowlist are touched — see | |
| 869 | + * FONT_CSS_HOSTS. Same-origin links (no host, or the site's own) never | |
| 870 | + * match the allowlist and are untouched. | |
| 871 | + * | |
| 872 | + * @param string $html Complete page HTML. | |
| 873 | + */ | |
| 874 | + public static function async_raw_font_css_links( $html ): string { | |
| 875 | + if ( ! is_string( $html ) || '' === $html ) { | |
| 876 | + return (string) $html; | |
| 877 | + } | |
| 878 | + if ( self::skip_in_non_frontend_context() ) { | |
| 879 | + return $html; | |
| 880 | + } | |
| 881 | + $opts = self::opts(); | |
| 882 | + if ( empty( $opts['async_css'] ) ) { | |
| 883 | + return $html; | |
| 884 | + } | |
| 885 | + | |
| 886 | + // Never rewrite inside a <noscript>. That block IS the no-JS | |
| 887 | + // fallback — its <link> is a plain blocking stylesheet on purpose, | |
| 888 | + // and async_style_tag() itself emits one for every sheet it defers. | |
| 889 | + // Rewriting it would nest <noscript> (invalid; the parser closes the | |
| 890 | + // outer block at the first </noscript>) and hand no-JS visitors a | |
| 891 | + // media="print" sheet whose onload never runs: no stylesheet at all. | |
| 892 | + // Splitting the buffer on <noscript> spans and rewriting only the | |
| 893 | + // slices between them also makes the pass idempotent against | |
| 894 | + // whatever an earlier pass emitted. | |
| 895 | + $parts = preg_split( | |
| 896 | + '#(<noscript\b[^>]*>.*?</noscript\s*>)#is', | |
| 897 | + $html, | |
| 898 | + -1, | |
| 899 | + PREG_SPLIT_DELIM_CAPTURE | |
| 900 | + ); | |
| 901 | + | |
| 902 | + // preg_split failed (pathological buffer / backtrack limit). Without | |
| 903 | + // the split we cannot tell a fallback link from a live one, so leave | |
| 904 | + // the page untouched — a few blocking font sheets beat a broken | |
| 905 | + // no-JS fallback. | |
| 906 | + if ( ! is_array( $parts ) ) { | |
| 907 | + return $html; | |
| 908 | + } | |
| 909 | + | |
| 910 | + foreach ( $parts as $i => $part ) { | |
| 911 | + // Odd indices are the captured <noscript> blocks. | |
| 912 | + if ( 1 === $i % 2 || '' === $part ) { | |
| 913 | + continue; | |
| 914 | + } | |
| 915 | + $parts[ $i ] = self::async_font_links_in_slice( $part ); | |
| 916 | + } | |
| 917 | + | |
| 918 | + return implode( '', $parts ); | |
| 919 | + } | |
| 920 | + | |
| 921 | + /** | |
| 922 | + * Rewrite the font-CSS links in one <noscript>-free slice of the buffer. | |
| 923 | + * | |
| 924 | + * @param string $html Slice of page HTML with no <noscript> spans. | |
| 925 | + */ | |
| 926 | + private static function async_font_links_in_slice( string $html ): string { | |
| 927 | + $hosts = self::font_css_hosts(); | |
| 928 | + | |
| 929 | + $out = preg_replace_callback( | |
| 930 | + '#<link\b[^>]*>#i', | |
| 931 | + static function ( array $m ) use ( $hosts ): string { | |
| 932 | + $tag = $m[0]; | |
| 933 | + | |
| 934 | + // Only plain stylesheets — never preload/alternate/anything | |
| 935 | + // carrying explicit author intent. `(?<![-\w])` not `\b`, so | |
| 936 | + // a `data-rel=` attribute can never read as the rel — same | |
| 937 | + // reason the delay passes spell src that way. (#273) | |
| 938 | + if ( ! preg_match( '#(?<![-\w])rel\s*=\s*(["\']?)\s*stylesheet\s*\1#i', $tag ) ) { | |
| 939 | + return $tag; | |
| 940 | + } | |
| 941 | + | |
| 942 | + // Already deferred (either marker spelling — ours and Pro's), | |
| 943 | + // or explicitly opted out by the theme. | |
| 944 | + foreach ( array( 'data-xs-async', 'data-xspeed-async', 'data-xspeed-keep' ) as $marker ) { | |
| 945 | + if ( false !== stripos( $tag, $marker ) ) { | |
| 946 | + return $tag; | |
| 947 | + } | |
| 948 | + } | |
| 949 | + | |
| 950 | + // An onload handler on a stylesheet link is only ever | |
| 951 | + // somebody's finished async pattern — same rule as | |
| 952 | + // async_style_tag(). (#216) | |
| 953 | + if ( preg_match( '#(?<![-\w])onload\s*=#i', $tag ) ) { | |
| 954 | + return $tag; | |
| 955 | + } | |
| 956 | + | |
| 957 | + // A sheet that never applies on screen is not blocking paint. | |
| 958 | + if ( preg_match( '#(?<![-\w])media\s*=\s*(["\'])([^"\']*)\1#i', $tag, $mm ) | |
| 959 | + && in_array( strtolower( trim( $mm[2] ) ), self::NON_SCREEN_MEDIA, true ) ) { | |
| 960 | + return $tag; | |
| 961 | + } | |
| 962 | + | |
| 963 | + if ( ! preg_match( '#(?<![-\w])href\s*=\s*(["\'])([^"\']+)\1#i', $tag, $hm ) ) { | |
| 964 | + return $tag; | |
| 965 | + } | |
| 966 | + // No host means a relative URL — same-origin, and the enqueue | |
| 967 | + // path's business if it is anybody's. | |
| 968 | + $host = strtolower( (string) wp_parse_url( $hm[2], PHP_URL_HOST ) ); | |
| 969 | + if ( '' === $host || ! in_array( $host, $hosts, true ) ) { | |
| 970 | + return $tag; | |
| 971 | + } | |
| 972 | + | |
| 973 | + return self::async_link_markup( $tag ); | |
| 974 | + }, | |
| 975 | + $html | |
| 976 | + ); | |
| 977 | + | |
| 978 | + // A PCRE failure returns null — the unrewritten slice is the safe | |
| 979 | + // fallback, never an empty page. | |
| 980 | + return null === $out ? $html : $out; | |
| 981 | + } | |
| 982 | + | |
| 983 | + /** | |
| 984 | + * Whether a stylesheet handle carries the page's layout, and so must | |
| 985 | + * keep blocking the first paint. | |
| 986 | + * | |
| 987 | + * Two families qualify: | |
| 988 | + * | |
| 989 | + * - The ACTIVE THEME's own sheets. A theme stylesheet is the page's | |
| 990 | + * layout by definition; without it the document paints as unstyled | |
| 991 | + * HTML. Resolved from the live theme's stem (`kadence` → | |
| 992 | + * `kadence-global`, `kadence-header`, …) plus the handles WordPress | |
| 993 | + * itself registers for a theme, so this holds for any theme rather | |
| 994 | + * than a hard-coded list. | |
| 995 | + * - WordPress' own BLOCK and layout sheets (`wp-block-library`, | |
| 996 | + * `global-styles`, `classic-theme-styles`). These style block | |
| 997 | + * content on the front end and are as structural as the theme's. | |
| 998 | + * | |
| 999 | + * Everything else — plugin sheets, icon fonts, widget and page-builder | |
| 1000 | + * add-ons, the long tail that makes async CSS worth having — is still | |
| 1001 | + * deferred, so the optimization keeps most of its benefit. | |
| 1002 | + * | |
| 1003 | + * A site WITH critical CSS can defer these too; that is what the | |
| 1004 | + * `xspeed_async_css_layout_critical` filter is for. | |
| 1005 | + * | |
| 1006 | + * Pure aside from the theme lookup — unit-tested via the filter. | |
| 1007 | + * | |
| 1008 | + * @param string $handle Stylesheet handle from `style_loader_tag`. | |
| 1009 | + */ | |
| 1010 | + public static function is_layout_critical_style( string $handle ): bool { | |
| 1011 | + $handle = strtolower( $handle ); | |
| 1012 | + | |
| 1013 | + // Core's front-end block + global styles. | |
| 1014 | + $core = array( | |
| 1015 | + 'wp-block-library', | |
| 1016 | + 'wp-block-library-theme', | |
| 1017 | + 'global-styles', | |
| 1018 | + 'classic-theme-styles', | |
| 1019 | + ); | |
| 1020 | + $critical = in_array( $handle, $core, true ); | |
| 1021 | + | |
| 1022 | + // The active theme's own sheets. | |
| 1023 | + // | |
| 1024 | + // Matched on the theme stem, but NOT as a bare prefix: a plugin from | |
| 1025 | + // the same vendor shares it (the Kadence theme is `kadence`, while | |
| 1026 | + // `kadence-blocks-rowlayout` and `kadence-fonts-gfonts` come from the | |
| 1027 | + // Kadence Blocks PLUGIN and a webfont loader). Treating those as | |
| 1028 | + // layout-critical would leave almost nothing deferred and quietly | |
| 1029 | + // undo the feature. So the stem must be followed by a recognised | |
| 1030 | + // theme-area segment, which is how themes name their split sheets. | |
| 1031 | + if ( ! $critical && function_exists( 'get_template' ) ) { | |
| 1032 | + $areas = array( | |
| 1033 | + 'style', | |
| 1034 | + 'global', | |
| 1035 | + 'header', | |
| 1036 | + 'content', | |
| 1037 | + 'footer', | |
| 1038 | + 'main', | |
| 1039 | + 'layout', | |
| 1040 | + 'base', | |
| 1041 | + 'core', | |
| 1042 | + 'theme', | |
| 1043 | + 'woocommerce', | |
| 1044 | + ); | |
| 1045 | + foreach ( array( get_template(), get_stylesheet() ) as $stem ) { | |
| 1046 | + $stem = strtolower( (string) $stem ); | |
| 1047 | + if ( '' === $stem ) { | |
| 1048 | + continue; | |
| 1049 | + } | |
| 1050 | + if ( $handle === $stem ) { | |
| 1051 | + $critical = true; | |
| 1052 | + break; | |
| 1053 | + } | |
| 1054 | + foreach ( $areas as $area ) { | |
| 1055 | + if ( $handle === $stem . '-' . $area ) { | |
| 1056 | + $critical = true; | |
| 1057 | + break 2; | |
| 1058 | + } | |
| 1059 | + } | |
| 1060 | + } | |
| 1061 | + } | |
| 1062 | + | |
| 1063 | + /** | |
| 1064 | + * Whether this stylesheet must keep blocking the first paint. | |
| 1065 | + * | |
| 1066 | + * Return false for a handle to let async CSS defer it anyway — the | |
| 1067 | + * right call on a site that ships critical CSS. Return true to | |
| 1068 | + * protect an additional sheet the layout depends on. | |
| 1069 | + * | |
| 1070 | + * @param bool $critical Whether the sheet is treated as layout-critical. | |
| 1071 | + * @param string $handle The stylesheet handle. | |
| 1072 | + */ | |
| 1073 | + return (bool) apply_filters( 'xspeed_async_css_layout_critical', $critical, $handle ); | |
| 1074 | + } | |
| 1075 | + | |
| 1076 | + /** | |
| 405 | 1077 | * Filter: `style_loader_src` + `script_loader_src` — strip the |
| 406 | 1078 | * ?ver=X.Y query string that WP appends for cache busting. Some |
| 407 | 1079 | * CDNs / reverse proxies cache better when the URL has no query. |
| 408 | 1080 | * |
| @@ -408,8 +1080,27 @@ | ||
| 408 | 1080 | * |
| 409 | 1081 | * Skip URLs whose query carries non-ver params — those might be |
| 410 | 1082 | * intentional (e.g. a CDN providing per-image transforms). |
| 411 | 1083 | * |
| 1084 | + * `ver` is load-bearing on one class of asset: a file a plugin | |
| 1085 | + * REGENERATES IN PLACE. Complianz rewrites | |
| 1086 | + * uploads/complianz/css/banner-1-optin.css whenever the banner is | |
| 1087 | + * edited, Beaver Builder rewrites uploads/bb-plugin/cache/<post>-layout.css | |
| 1088 | + * on every layout save, Elementor uploads/elementor/css/post-<id>.css on | |
| 1089 | + * publish. The path never changes, so `?ver=<timestamp|hash>` is the only | |
| 1090 | + * thing telling a browser — or our own Browser Cache `immutable` rule — to | |
| 1091 | + * refetch. Strip it and the old styling is served until the browser cache | |
| 1092 | + * gives up, which for us is a year. So anything under the uploads root | |
| 1093 | + * keeps its version. | |
| 1094 | + * | |
| 1095 | + * Release assets under plugins/, themes/ and core are still stripped, but | |
| 1096 | + * not because they are safe: an update overwrites the same path there too, | |
| 1097 | + * and only `?ver=` changed. The difference is frequency, not mechanism — a | |
| 1098 | + * plugin update lands rarely and is expected to, a banner edit is a setting | |
| 1099 | + * the user just changed and expects to see. Stripping is the feature the | |
| 1100 | + * toggle is for; with Browser Cache on it is what the user is buying, and | |
| 1101 | + * `docs/user/minification.md` states the cost. (#276) | |
| 1102 | + * | |
| 412 | 1103 | * @param string $src |
| 413 | 1104 | */ |
| 414 | 1105 | public static function strip_version_query( $src ): string { |
| 415 | 1106 | if ( ! is_string( $src ) || '' === $src ) { |
| @@ -422,17 +1113,46 @@ | ||
| 422 | 1113 | if ( ! is_array( $parts ) || empty( $parts['query'] ) ) { |
| 423 | 1114 | return $src; |
| 424 | 1115 | } |
| 425 | 1116 | parse_str( $parts['query'], $query ); |
| 426 | - if ( ! is_array( $query ) ) { | |
| 1117 | + if ( ! is_array( $query ) || ! array_key_exists( 'ver', $query ) ) { | |
| 427 | 1118 | return $src; |
| 428 | 1119 | } |
| 1120 | + | |
| 1121 | + $strip = ! self::is_regenerated_asset( $parts ); | |
| 1122 | + | |
| 1123 | + /** | |
| 1124 | + * Whether Remove Query Strings drops `?ver` from this asset URL. | |
| 1125 | + * | |
| 1126 | + * False by default under the uploads root, where page builders and | |
| 1127 | + * consent plugins rewrite generated CSS/JS in place and `ver` is its | |
| 1128 | + * only cache-buster. Return false to protect a generator that writes | |
| 1129 | + * somewhere else, true to force stripping. | |
| 1130 | + * | |
| 1131 | + * @param bool $strip Whether `ver` will be removed. | |
| 1132 | + * @param string $src The asset URL as enqueued. | |
| 1133 | + */ | |
| 1134 | + if ( ! apply_filters( 'xspeed_strip_asset_version', $strip, $src ) ) { | |
| 1135 | + return $src; | |
| 1136 | + } | |
| 1137 | + | |
| 429 | 1138 | // Only strip 'ver' — keep anything else the asset URL needs. |
| 430 | 1139 | unset( $query['ver'] ); |
| 431 | 1140 | $new_query = http_build_query( $query ); |
| 432 | - $new_url = ( $parts['scheme'] ?? 'http' ) . '://' . ( $parts['host'] ?? '' ); | |
| 433 | - if ( isset( $parts['port'] ) ) { | |
| 434 | - $new_url .= ':' . $parts['port']; | |
| 1141 | + | |
| 1142 | + // Rebuild the authority only when the source had one. An enqueued | |
| 1143 | + // src is not always absolute: `//cdn.example/x.css` says "the | |
| 1144 | + // page's own scheme", and defaulting that to http:// is mixed | |
| 1145 | + // content an https page blocks outright; `/wp-includes/x.js` has no | |
| 1146 | + // host at all, and pasting one in produced `http:///wp-includes/…`, | |
| 1147 | + // which resolves nowhere. | |
| 1148 | + $new_url = ''; | |
| 1149 | + if ( isset( $parts['host'] ) && '' !== $parts['host'] ) { | |
| 1150 | + $new_url = isset( $parts['scheme'] ) ? $parts['scheme'] . '://' : '//'; | |
| 1151 | + $new_url .= $parts['host']; | |
| 1152 | + if ( isset( $parts['port'] ) ) { | |
| 1153 | + $new_url .= ':' . $parts['port']; | |
| 1154 | + } | |
| 435 | 1155 | } |
| 436 | 1156 | $new_url .= $parts['path'] ?? ''; |
| 437 | 1157 | if ( '' !== $new_query ) { |
| 438 | 1158 | $new_url .= '?' . $new_query; |
| @@ -443,8 +1163,80 @@ | ||
| 443 | 1163 | return $new_url; |
| 444 | 1164 | } |
| 445 | 1165 | |
| 446 | 1166 | /** |
| 1167 | + * Memoised uploads root, see uploads_base(). Cleared by reset_state(). | |
| 1168 | + * | |
| 1169 | + * @var array{host:string,path:string}|null | |
| 1170 | + */ | |
| 1171 | + private static $uploads_base = null; | |
| 1172 | + | |
| 1173 | + /** | |
| 1174 | + * The uploads root as a URL host + PATH, read from wp_get_upload_dir() | |
| 1175 | + * rather than hardcoded so a moved uploads dir, the `UPLOADS` constant and | |
| 1176 | + * the legacy multisite `/files/` layout all work. | |
| 1177 | + * | |
| 1178 | + * On multisite wp_get_upload_dir() answers with the per-site | |
| 1179 | + * `…/uploads/sites/<id>`. Generated assets live under the network root | |
| 1180 | + * too, so the suffix comes off and the whole tree matches. | |
| 1181 | + * | |
| 1182 | + * @return array{host:string,path:string} | |
| 1183 | + */ | |
| 1184 | + private static function uploads_base(): array { | |
| 1185 | + if ( null !== self::$uploads_base ) { | |
| 1186 | + return self::$uploads_base; | |
| 1187 | + } | |
| 1188 | + $base = ''; | |
| 1189 | + if ( function_exists( 'wp_get_upload_dir' ) ) { | |
| 1190 | + $dir = wp_get_upload_dir(); | |
| 1191 | + $base = is_array( $dir ) && isset( $dir['baseurl'] ) ? (string) $dir['baseurl'] : ''; | |
| 1192 | + } | |
| 1193 | + $host = ''; | |
| 1194 | + $path = ''; | |
| 1195 | + if ( '' !== $base ) { | |
| 1196 | + $host = strtolower( (string) wp_parse_url( $base, PHP_URL_HOST ) ); | |
| 1197 | + $path = (string) wp_parse_url( $base, PHP_URL_PATH ); | |
| 1198 | + } | |
| 1199 | + $path = (string) preg_replace( '#/sites/\d+/?$#', '', rtrim( $path, '/' ) ); | |
| 1200 | + if ( '' === $path && '' === $host ) { | |
| 1201 | + // Unreadable. An empty prefix would match every asset on the | |
| 1202 | + // site, so fall back to where uploads normally is. | |
| 1203 | + $path = '/wp-content/uploads'; | |
| 1204 | + } | |
| 1205 | + self::$uploads_base = array( | |
| 1206 | + 'host' => $host, | |
| 1207 | + 'path' => $path, | |
| 1208 | + ); | |
| 1209 | + return self::$uploads_base; | |
| 1210 | + } | |
| 1211 | + | |
| 1212 | + /** | |
| 1213 | + * Does this URL sit under the uploads root — i.e. is it a file some plugin | |
| 1214 | + * generates at runtime and rewrites in place? | |
| 1215 | + * | |
| 1216 | + * @param array<string,mixed> $parts wp_parse_url() output for the asset. | |
| 1217 | + */ | |
| 1218 | + private static function is_regenerated_asset( array $parts ): bool { | |
| 1219 | + $base = self::uploads_base(); | |
| 1220 | + | |
| 1221 | + if ( '' !== $base['path'] ) { | |
| 1222 | + // Path only, never host: a pull-zone CDN, a protocol-relative URL | |
| 1223 | + // and an http/https flip all leave the path alone. | |
| 1224 | + $path = (string) ( $parts['path'] ?? '' ); | |
| 1225 | + return '' !== $path && 0 === strpos( $path, $base['path'] . '/' ); | |
| 1226 | + } | |
| 1227 | + | |
| 1228 | + // Uploads AT the root of their own domain — an offload plugin | |
| 1229 | + // pointing `upload_url_path` at https://cdn.example.com. There is no | |
| 1230 | + // prefix left to test, and testing the path anyway would have read | |
| 1231 | + // every generated file on that CDN as an ordinary release asset and | |
| 1232 | + // stripped the one thing telling a browser it had changed. The host | |
| 1233 | + // is the whole answer here: everything served from it is an upload. | |
| 1234 | + $host = strtolower( (string) ( $parts['host'] ?? '' ) ); | |
| 1235 | + return '' !== $host && $host === $base['host']; | |
| 1236 | + } | |
| 1237 | + | |
| 1238 | + /** | |
| 447 | 1239 | * Defensive context guard for filter callbacks. Mirrors the registration- |
| 448 | 1240 | * time bail in Minifier::__construct() so a late context flip (admin page |
| 449 | 1241 | * render kicked off mid-request, REST_REQUEST set after plugins_loaded, |
| 450 | 1242 | * etc.) doesn't let frontend tag rewrites leak into wp-admin / AJAX / |
| @@ -511,8 +1303,52 @@ | ||
| 511 | 1303 | * page's JS. Empty targets = historical behavior (delay everything |
| 512 | 1304 | * minus exclusions). Same matching semantics as the exclusion list: |
| 513 | 1305 | * exact handle match OR case-insensitive URL substring. |
| 514 | 1306 | */ |
| 1307 | + /** | |
| 1308 | + * Whether the user's delay_js_targets list matches this haystack. | |
| 1309 | + * | |
| 1310 | + * The inline-snippet pass needs the target list WITHOUT | |
| 1311 | + * is_delay_target()'s empty-list-means-everything default — an inline | |
| 1312 | + * body is only ever delayed on a positive match. | |
| 1313 | + * | |
| 1314 | + * @param string $haystack Script body (or URL) to match fragments against. | |
| 1315 | + */ | |
| 1316 | + private static function matches_user_targets( string $haystack ): bool { | |
| 1317 | + $opts = self::opts(); | |
| 1318 | + $targets = is_array( $opts['delay_js_targets'] ?? null ) ? $opts['delay_js_targets'] : array(); | |
| 1319 | + foreach ( $targets as $needle ) { | |
| 1320 | + $needle = (string) $needle; | |
| 1321 | + if ( '' !== $needle && false !== stripos( $haystack, $needle ) ) { | |
| 1322 | + return true; | |
| 1323 | + } | |
| 1324 | + } | |
| 1325 | + return false; | |
| 1326 | + } | |
| 1327 | + | |
| 1328 | + /** | |
| 1329 | + * Whether the user EXPLICITLY named this script in delay_js_targets. | |
| 1330 | + * | |
| 1331 | + * Unlike is_delay_target() this never treats an empty list as | |
| 1332 | + * everything and never falls back to the vendor list — it answers | |
| 1333 | + * only "did the user deliberately point at this handle/URL?", which | |
| 1334 | + * is what lets an explicit entry override the inline-bound guard. | |
| 1335 | + * | |
| 1336 | + * @param string $handle Script handle. | |
| 1337 | + * @param string $src Script URL. | |
| 1338 | + */ | |
| 1339 | + private static function is_user_named_target( string $handle, string $src ): bool { | |
| 1340 | + $opts = self::opts(); | |
| 1341 | + $targets = is_array( $opts['delay_js_targets'] ?? null ) ? $opts['delay_js_targets'] : array(); | |
| 1342 | + foreach ( $targets as $needle ) { | |
| 1343 | + $needle = (string) $needle; | |
| 1344 | + if ( '' !== $needle && self::target_matches( $needle, $handle, $src ) ) { | |
| 1345 | + return true; | |
| 1346 | + } | |
| 1347 | + } | |
| 1348 | + return false; | |
| 1349 | + } | |
| 1350 | + | |
| 515 | 1351 | private static function is_delay_target( string $handle, string $src ): bool { |
| 516 | 1352 | $opts = self::opts(); |
| 517 | 1353 | $targets = is_array( $opts['delay_js_targets'] ?? null ) ? $opts['delay_js_targets'] : array(); |
| 518 | 1354 | $targets = array_filter( array_map( 'strval', $targets ), static fn( $t ) => '' !== $t ); |
| @@ -523,8 +1359,116 @@ | ||
| 523 | 1359 | if ( self::target_matches( $needle, $handle, $src ) ) { |
| 524 | 1360 | return true; |
| 525 | 1361 | } |
| 526 | 1362 | } |
| 1363 | + // The user's list is an ALLOW-list, so a target they never thought to | |
| 1364 | + // add is not delayed — and the scripts worth delaying are third-party | |
| 1365 | + // tags nobody enumerates by hand. Falling back to the built-in vendor | |
| 1366 | + // list means a site that lists one heavy embed still gets the obvious | |
| 1367 | + // analytics and widget tags postponed, instead of silently keeping | |
| 1368 | + // them on the main thread. (A user who wants one of these to run | |
| 1369 | + // early excludes it; the exclusion list is checked before this.) | |
| 1370 | + return self::matches_known_third_party( $src ); | |
| 1371 | + } | |
| 1372 | + | |
| 1373 | + /** | |
| 1374 | + * Whether a URL belongs to a third-party tag that is safe to postpone. | |
| 1375 | + * | |
| 1376 | + * These are analytics, tag managers, chat widgets, review embeds, session | |
| 1377 | + * recorders and error trackers: scripts that never paint anything above | |
| 1378 | + * the fold and that no first-party code holds a synchronous reference to. | |
| 1379 | + * They are also the scripts that dominate a real page's blocking time — | |
| 1380 | + * on embedpress.com one chat widget alone accounted for ~450ms of TBT and | |
| 1381 | + * a 22-point score swing between runs, purely on whether it happened to | |
| 1382 | + * arrive inside the measurement window. | |
| 1383 | + * | |
| 1384 | + * Matched on URL only, never on handle: these tags are printed straight | |
| 1385 | + * into wp_head / wp_footer by their vendors' snippets and usually have no | |
| 1386 | + * WordPress handle at all. Host fragments rather than whole domains, so a | |
| 1387 | + * regional or versioned CDN path still matches. | |
| 1388 | + * | |
| 1389 | + * Deliberately NOT here: anything from the site's own origin, jQuery, or | |
| 1390 | + * any wp-* core script. Those carry inline consumers, and delaying them | |
| 1391 | + * is what breaks pages — see inline_bound_handles(). | |
| 1392 | + */ | |
| 1393 | + private const KNOWN_THIRD_PARTY_SRC = array( | |
| 1394 | + // Tag managers and analytics. | |
| 1395 | + 'googletagmanager.com', | |
| 1396 | + 'google-analytics.com', | |
| 1397 | + 'analytics.google.com', | |
| 1398 | + '/gtag/js', | |
| 1399 | + 'gtm4wp', | |
| 1400 | + 'plausible.io', | |
| 1401 | + 'matomo', | |
| 1402 | + 'segment.com/analytics.js', | |
| 1403 | + 'stats.wp.com', | |
| 1404 | + // Advertising and conversion pixels. | |
| 1405 | + 'connect.facebook.net', | |
| 1406 | + 'fbevents.js', | |
| 1407 | + 'ads-twitter.com', | |
| 1408 | + 'snap.licdn.com', | |
| 1409 | + 'analytics.tiktok.com', | |
| 1410 | + 'googleadservices.com', | |
| 1411 | + 'doubleclick.net', | |
| 1412 | + // Session recording and heatmaps. | |
| 1413 | + 'hotjar.com', | |
| 1414 | + 'clarity.ms', | |
| 1415 | + 'mouseflow.com', | |
| 1416 | + 'fullstory.com', | |
| 1417 | + 'luckyorange', | |
| 1418 | + // Chat and support widgets. | |
| 1419 | + 'client.crisp.chat', | |
| 1420 | + 'widget.intercom.io', | |
| 1421 | + 'js.driftt.com', | |
| 1422 | + 'tawk.to', | |
| 1423 | + 'livechatinc.com', | |
| 1424 | + 'zdassets.com', | |
| 1425 | + 'helpscout.net', | |
| 1426 | + // Reviews, social proof and marketing. | |
| 1427 | + 'tp.widget.bootstrap', | |
| 1428 | + 'trustpilot.com', | |
| 1429 | + 'static.klaviyo.com', | |
| 1430 | + 'js.hs-scripts.com', | |
| 1431 | + 'list-manage.com', | |
| 1432 | + 'sumo.com', | |
| 1433 | + // Error and performance monitoring. | |
| 1434 | + 'sentry-cdn.com', | |
| 1435 | + 'browser.sentry', | |
| 1436 | + 'bugsnag.com', | |
| 1437 | + 'newrelic.com', | |
| 1438 | + ); | |
| 1439 | + | |
| 1440 | + /** | |
| 1441 | + * Match a script URL against the built-in third-party list. | |
| 1442 | + * | |
| 1443 | + * @param string $src Script source URL. | |
| 1444 | + */ | |
| 1445 | + private static function matches_known_third_party( string $src ): bool { | |
| 1446 | + if ( '' === $src ) { | |
| 1447 | + return false; | |
| 1448 | + } | |
| 1449 | + | |
| 1450 | + $known = self::KNOWN_THIRD_PARTY_SRC; | |
| 1451 | + | |
| 1452 | + /** | |
| 1453 | + * URL fragments the delay pass treats as safe-to-postpone third-party | |
| 1454 | + * tags when the user's target list does not match. | |
| 1455 | + * | |
| 1456 | + * Append a vendor this list does not know yet, or remove one the site | |
| 1457 | + * genuinely needs early. Entries are case-insensitive substrings of | |
| 1458 | + * the script URL. | |
| 1459 | + * | |
| 1460 | + * @param string[] $known Built-in fragments. | |
| 1461 | + * @param string $src The script URL being tested. | |
| 1462 | + */ | |
| 1463 | + $known = (array) apply_filters( 'xspeed_delay_known_third_party', $known, $src ); | |
| 1464 | + | |
| 1465 | + foreach ( $known as $needle ) { | |
| 1466 | + $needle = (string) $needle; | |
| 1467 | + if ( '' !== $needle && false !== stripos( $src, $needle ) ) { | |
| 1468 | + return true; | |
| 1469 | + } | |
| 1470 | + } | |
| 527 | 1471 | return false; |
| 528 | 1472 | } |
| 529 | 1473 | |
| 530 | 1474 | private static function opts(): array { |
| @@ -538,7 +1482,248 @@ | ||
| 538 | 1482 | * Test-only — clear cached opts + bootstrap-printed flag. |
| 539 | 1483 | */ |
| 540 | 1484 | public static function reset_state(): void { |
| 541 | 1485 | self::$opts = null; |
| 1486 | + self::$uploads_base = null; | |
| 542 | 1487 | self::$delay_bootstrap_printed = false; |
| 1488 | + self::$js_measured_layout = null; | |
| 1489 | + self::$inline_bound_handles = null; | |
| 1490 | + } | |
| 1491 | + | |
| 1492 | + /** | |
| 1493 | + * Per-request memo for inline_bound_handles(). Null = not resolved. | |
| 1494 | + * | |
| 1495 | + * @var array<string,true>|null | |
| 1496 | + */ | |
| 1497 | + private static $inline_bound_handles = null; | |
| 1498 | + | |
| 1499 | + /** | |
| 1500 | + * Handles that cannot be deferred because inline code depends on them. | |
| 1501 | + * | |
| 1502 | + * #234 fixed the case where a handle carries its OWN inline block: the | |
| 1503 | + * tag WordPress hands the filter is `before_inline + external + | |
| 1504 | + * after_inline`, so defer goes on the external <script> and order holds. | |
| 1505 | + * That leaves the cross-handle case, which is the one that actually | |
| 1506 | + * breaks sites: `wp_add_inline_script( 'foo', … )` prints a bare inline | |
| 1507 | + * block that runs at parse time and calls into whatever `foo` — or any | |
| 1508 | + * of foo's DEPENDENCIES — defined. Inline scripts can never be deferred | |
| 1509 | + * (the HTML spec ignores the attribute), so deferring anything they read | |
| 1510 | + * from inverts the order WordPress guarantees and throws on a global | |
| 1511 | + * that is not there yet. | |
| 1512 | + * | |
| 1513 | + * jQuery is the canonical victim: one `wp_add_inline_script( 'jquery', | |
| 1514 | + * 'jQuery(function($){…})' )` anywhere on the page makes `jquery-core` | |
| 1515 | + * undeferrable, and every hand-maintained exclusion list in the wild | |
| 1516 | + * exists to say so. The registry already knows it, so read it instead of | |
| 1517 | + * asking the user. | |
| 1518 | + * | |
| 1519 | + * Walks each handle carrying `after`/`before` inline data and marks the | |
| 1520 | + * handle plus its transitive dependency chain. Cycles are guarded by the | |
| 1521 | + * seen-map, so a self- or mutually-referential deps array terminates. | |
| 1522 | + * | |
| 1523 | + * Pure aside from the global registry read; memoised per request and | |
| 1524 | + * cleared by reset_state(). | |
| 1525 | + * | |
| 1526 | + * @return array<string,true> Handle => true, for O(1) lookup. | |
| 1527 | + */ | |
| 1528 | + public static function inline_bound_handles(): array { | |
| 1529 | + if ( null !== self::$inline_bound_handles ) { | |
| 1530 | + return self::$inline_bound_handles; | |
| 1531 | + } | |
| 1532 | + | |
| 1533 | + $bound = array(); | |
| 1534 | + if ( function_exists( 'wp_scripts' ) ) { | |
| 1535 | + $scripts = wp_scripts(); | |
| 1536 | + if ( $scripts instanceof \WP_Scripts ) { | |
| 1537 | + foreach ( array_keys( (array) $scripts->registered ) as $handle ) { | |
| 1538 | + $handle = (string) $handle; | |
| 1539 | + if ( ! self::handle_carries_inline( $scripts, $handle ) ) { | |
| 1540 | + continue; | |
| 1541 | + } | |
| 1542 | + self::mark_with_deps( $scripts, $handle, $bound ); | |
| 1543 | + } | |
| 1544 | + } | |
| 1545 | + } | |
| 1546 | + | |
| 1547 | + /** | |
| 1548 | + * Handles auto-excluded from defer because inline code reads them. | |
| 1549 | + * | |
| 1550 | + * Return a handle => true map. Add an entry to protect a script whose | |
| 1551 | + * inline consumer this cannot see (one printed directly by a theme | |
| 1552 | + * rather than through wp_add_inline_script), or remove one to defer a | |
| 1553 | + * handle whose inline block is known not to touch it. | |
| 1554 | + * | |
| 1555 | + * @param array<string,true> $bound Detected handles. | |
| 1556 | + */ | |
| 1557 | + $bound = (array) apply_filters( 'xspeed_defer_inline_bound_handles', $bound ); | |
| 1558 | + | |
| 1559 | + self::$inline_bound_handles = $bound; | |
| 1560 | + | |
| 1561 | + return self::$inline_bound_handles; | |
| 1562 | + } | |
| 1563 | + | |
| 1564 | + /** | |
| 1565 | + * Whether a handle must be kept out of a combined bundle. | |
| 1566 | + * | |
| 1567 | + * Combining re-homes a script's code under a different handle, so every | |
| 1568 | + * protection keyed to the ORIGINAL handle or URL stops matching: the | |
| 1569 | + * user's `defer_js_excluded` entry, and the inline-bound set above. The | |
| 1570 | + * combiner already refuses a handle carrying its own inline data, which | |
| 1571 | + * is why the gap is invisible until you look for it — a DEPENDENCY of an | |
| 1572 | + * inline consumer carries none of its own, so `jquery-core` lands in the | |
| 1573 | + * bundle while the exclusion list still reads as though it were honoured. | |
| 1574 | + * | |
| 1575 | + * Returning true here is enough on its own: the combiner drops any | |
| 1576 | + * dependent of an uncombinable handle transitively, so the whole chain | |
| 1577 | + * stays in the queue where WordPress prints it in the right order. | |
| 1578 | + * | |
| 1579 | + * @param string $handle Script handle. | |
| 1580 | + * @param string $src Registered source URL. | |
| 1581 | + */ | |
| 1582 | + public static function is_protected_from_bundling( string $handle, string $src ): bool { | |
| 1583 | + if ( self::is_excluded_script( $handle, $src ) ) { | |
| 1584 | + return true; | |
| 1585 | + } | |
| 1586 | + return isset( self::inline_bound_handles()[ $handle ] ); | |
| 1587 | + } | |
| 1588 | + | |
| 1589 | + /** | |
| 1590 | + * Whether a handle has inline JS attached in either position. | |
| 1591 | + * | |
| 1592 | + * `get_data()` returns the raw value, which is an array of code chunks | |
| 1593 | + * for `after` and a string for `before`; both are falsy when absent, and | |
| 1594 | + * an empty chunk array must not count as inline code. | |
| 1595 | + * | |
| 1596 | + * @param \WP_Scripts $scripts Registry. | |
| 1597 | + * @param string $handle Handle to inspect. | |
| 1598 | + */ | |
| 1599 | + private static function handle_carries_inline( \WP_Scripts $scripts, string $handle ): bool { | |
| 1600 | + foreach ( array( 'after', 'before' ) as $position ) { | |
| 1601 | + $data = $scripts->get_data( $handle, $position ); | |
| 1602 | + if ( is_array( $data ) ) { | |
| 1603 | + foreach ( $data as $chunk ) { | |
| 1604 | + if ( '' !== trim( (string) $chunk ) ) { | |
| 1605 | + return true; | |
| 1606 | + } | |
| 1607 | + } | |
| 1608 | + continue; | |
| 1609 | + } | |
| 1610 | + if ( '' !== trim( (string) $data ) ) { | |
| 1611 | + return true; | |
| 1612 | + } | |
| 1613 | + } | |
| 1614 | + return false; | |
| 1615 | + } | |
| 1616 | + | |
| 1617 | + /** | |
| 1618 | + * Mark a handle and everything it depends on, transitively. | |
| 1619 | + * | |
| 1620 | + * @param \WP_Scripts $scripts Registry. | |
| 1621 | + * @param string $handle Handle to mark. | |
| 1622 | + * @param array<string,true> $seen Accumulator, by reference. | |
| 1623 | + */ | |
| 1624 | + private static function mark_with_deps( \WP_Scripts $scripts, string $handle, array &$seen ): void { | |
| 1625 | + if ( isset( $seen[ $handle ] ) ) { | |
| 1626 | + return; | |
| 1627 | + } | |
| 1628 | + $seen[ $handle ] = true; | |
| 1629 | + if ( ! isset( $scripts->registered[ $handle ]->deps ) ) { | |
| 1630 | + return; | |
| 1631 | + } | |
| 1632 | + foreach ( (array) $scripts->registered[ $handle ]->deps as $dep ) { | |
| 1633 | + self::mark_with_deps( $scripts, (string) $dep, $seen ); | |
| 1634 | + } | |
| 1635 | + } | |
| 1636 | + | |
| 1637 | + /** | |
| 1638 | + * Per-request memo for page_has_js_measured_layout(). Null = not resolved. | |
| 1639 | + * | |
| 1640 | + * @var bool|null | |
| 1641 | + */ | |
| 1642 | + private static $js_measured_layout = null; | |
| 1643 | + | |
| 1644 | + /** | |
| 1645 | + * Scripts that lay out the page by measuring the DOM. | |
| 1646 | + * | |
| 1647 | + * Each of these reads element sizes and then writes positions. If the CSS | |
| 1648 | + * that sizes those elements has not applied when the script runs, it | |
| 1649 | + * measures the wrong values and commits a broken layout that no later | |
| 1650 | + * stylesheet can correct. | |
| 1651 | + * | |
| 1652 | + * Matched as a substring of the registered handle, so a plugin shipping | |
| 1653 | + * `acme-masonry` or `masonry-init` is covered without naming it here. | |
| 1654 | + * | |
| 1655 | + * @return string[] | |
| 1656 | + */ | |
| 1657 | + private static function js_layout_script_markers(): array { | |
| 1658 | + return array( | |
| 1659 | + 'masonry', | |
| 1660 | + 'isotope', | |
| 1661 | + 'packery', | |
| 1662 | + 'salvattore', | |
| 1663 | + 'justified-gallery', | |
| 1664 | + 'slick', | |
| 1665 | + 'splide', | |
| 1666 | + 'swiper', | |
| 1667 | + 'flickity', | |
| 1668 | + 'owl-carousel', | |
| 1669 | + 'matchheight', | |
| 1670 | + ); | |
| 1671 | + } | |
| 1672 | + | |
| 1673 | + /** | |
| 1674 | + * True when a script that measures the DOM to build a layout is enqueued | |
| 1675 | + * for this request. | |
| 1676 | + * | |
| 1677 | + * Reads the enqueue registry rather than the finished HTML, because this | |
| 1678 | + * runs on `style_loader_tag` — while the head is being printed, before any | |
| 1679 | + * body markup exists to scan. Both the queue and each queued handle's | |
| 1680 | + * dependencies are checked: core registers `masonry` as a DEPENDENCY of a | |
| 1681 | + * plugin's init script, so it is frequently absent from the queue itself. | |
| 1682 | + * | |
| 1683 | + * Pure aside from the global registry read; the result is memoised per | |
| 1684 | + * request and cleared by reset_state(). | |
| 1685 | + */ | |
| 1686 | + public static function page_has_js_measured_layout(): bool { | |
| 1687 | + if ( null !== self::$js_measured_layout ) { | |
| 1688 | + return self::$js_measured_layout; | |
| 1689 | + } | |
| 1690 | + | |
| 1691 | + $found = false; | |
| 1692 | + if ( function_exists( 'wp_scripts' ) ) { | |
| 1693 | + $scripts = wp_scripts(); | |
| 1694 | + if ( $scripts instanceof \WP_Scripts ) { | |
| 1695 | + $handles = (array) $scripts->queue; | |
| 1696 | + // Pull in dependencies — `masonry` usually arrives that way. | |
| 1697 | + foreach ( (array) $scripts->queue as $queued ) { | |
| 1698 | + if ( isset( $scripts->registered[ $queued ]->deps ) ) { | |
| 1699 | + $handles = array_merge( $handles, (array) $scripts->registered[ $queued ]->deps ); | |
| 1700 | + } | |
| 1701 | + } | |
| 1702 | + $markers = self::js_layout_script_markers(); | |
| 1703 | + foreach ( $handles as $handle ) { | |
| 1704 | + $handle = strtolower( (string) $handle ); | |
| 1705 | + foreach ( $markers as $marker ) { | |
| 1706 | + if ( false !== strpos( $handle, $marker ) ) { | |
| 1707 | + $found = true; | |
| 1708 | + break 2; | |
| 1709 | + } | |
| 1710 | + } | |
| 1711 | + } | |
| 1712 | + } | |
| 1713 | + } | |
| 1714 | + | |
| 1715 | + /** | |
| 1716 | + * Whether this request renders a JS-measured layout, making async CSS | |
| 1717 | + * unsafe for the whole page. | |
| 1718 | + * | |
| 1719 | + * Return false to defer anyway (a site that ships critical CSS, or one | |
| 1720 | + * whose grid is pure CSS), or true to protect a library not detected | |
| 1721 | + * by handle. | |
| 1722 | + * | |
| 1723 | + * @param bool $found Whether a measuring script was detected. | |
| 1724 | + */ | |
| 1725 | + self::$js_measured_layout = (bool) apply_filters( 'xspeed_async_css_js_measured_layout', $found ); | |
| 1726 | + | |
| 1727 | + return self::$js_measured_layout; | |
| 543 | 1728 | } |
| 544 | 1729 | } |