| @@ -82,8 +82,395 @@ | ||
| 82 | 82 | self::$original_src = array(); |
| 83 | 83 | } |
| 84 | 84 | |
| 85 | 85 | /** |
| 86 | + * Does this tag (or attribute string) opt out of optimization? | |
| 87 | + * | |
| 88 | + * `data-no-optimize` / `data-no-minify` are the de-facto convention | |
| 89 | + * consent managers and other plugins print so optimizers keep hands | |
| 90 | + * off (Borlabs Cookie stamps both on its config script). The CSS | |
| 91 | + * combine buffer has honored `data-no-optimize` from the start; the | |
| 92 | + * JS paths did not, so a marked consent script was still minified | |
| 93 | + * into a hashed cache file — and a stale copy of a legally relevant | |
| 94 | + * consent config is a correctness problem, not a cosmetic one. (#456) | |
| 95 | + * | |
| 96 | + * @param string $tag A full tag, or just its attribute string. | |
| 97 | + */ | |
| 98 | + public static function tag_opts_out( string $tag ): bool { | |
| 99 | + return (bool) preg_match( '#\sdata-no-(?:optimize|minify)\b#i', $tag ); | |
| 100 | + } | |
| 101 | + | |
| 102 | + /** | |
| 103 | + * Pristine tags as they looked before any of our transforms, keyed by | |
| 104 | + * handle. See snapshot_tag() / revert_late_marked_tag(). | |
| 105 | + * | |
| 106 | + * @var array<string,string> | |
| 107 | + */ | |
| 108 | + private static $pristine_tag = array(); | |
| 109 | + | |
| 110 | + /** | |
| 111 | + * Priority for the late opt-out re-check. Past Borlabs' ScriptBlocker | |
| 112 | + * at 999 — the highest stamper we have seen in the wild — so the | |
| 113 | + * marker has certainly landed by the time we look. (#469) | |
| 114 | + */ | |
| 115 | + private const LATE_OPT_OUT_PRIORITY = 1000; | |
| 116 | + | |
| 117 | + /** | |
| 118 | + * The priority the late opt-out re-check runs at. | |
| 119 | + * | |
| 120 | + * A site whose stamper hooks even later can move ours past it. | |
| 121 | + */ | |
| 122 | + public static function late_opt_out_priority(): int { | |
| 123 | + /** | |
| 124 | + * Filter the priority of xSpeed's late data-no-optimize re-check. | |
| 125 | + * | |
| 126 | + * @param int $priority Default 1000. | |
| 127 | + */ | |
| 128 | + return (int) apply_filters( 'xspeed_late_opt_out_priority', self::LATE_OPT_OUT_PRIORITY ); | |
| 129 | + } | |
| 130 | + | |
| 131 | + /** | |
| 132 | + * Filter: `script_loader_tag`, priority 9 — remember the tag before we | |
| 133 | + * touch it, so a marker stamped later can still be honored. | |
| 134 | + * | |
| 135 | + * Our three opt-out-aware transforms run at 15/20/30. A plugin that | |
| 136 | + * stamps `data-no-optimize` AFTER them is invisible to all three: | |
| 137 | + * Borlabs Cookie stamps at priority 100, so its consent config was | |
| 138 | + * still minified into a hashed cache file AND delayed — the script | |
| 139 | + * that has to run before anything else on the page ran only on first | |
| 140 | + * interaction. Snapshotting here is what lets the late pass put the | |
| 141 | + * original back verbatim, rather than trying to unpick each transform | |
| 142 | + * in reverse. (#469) | |
| 143 | + * | |
| 144 | + * @param string $tag | |
| 145 | + * @param string $handle | |
| 146 | + * @param string $src | |
| 147 | + */ | |
| 148 | + public static function snapshot_tag( $tag, $handle, $src ): string { | |
| 149 | + if ( is_string( $tag ) && '' !== $tag && '' !== (string) $handle ) { | |
| 150 | + self::$pristine_tag[ (string) $handle ] = $tag; | |
| 151 | + } | |
| 152 | + return (string) $tag; | |
| 153 | + } | |
| 154 | + | |
| 155 | + /** | |
| 156 | + * Filter: `script_loader_tag`, priority `LATE_OPT_OUT_PRIORITY` — hand | |
| 157 | + * back the untouched tag when a late filter stamped an opt-out marker | |
| 158 | + * after our transforms had already run. | |
| 159 | + * | |
| 160 | + * The priority has to clear the stamper, not merely the transforms: | |
| 161 | + * Borlabs stamps at 100 and Borlabs' own script blocker at 999, so an | |
| 162 | + * earlier hook reads a tag whose marker has not landed yet. PHP_INT_MAX | |
| 163 | + * would be unfriendly to a site that legitimately wants the last word, | |
| 164 | + * so this sits just past the highest stamper we know of and is | |
| 165 | + * filterable. Reverting to the snapshot is deliberate: undoing | |
| 166 | + * a delay rewrite in place would mean re-deriving `src` from | |
| 167 | + * `data-xs-src` and stripping markers, and #273 is a standing reminder | |
| 168 | + * that regex-editing these attributes in reverse goes wrong quietly. | |
| 169 | + * | |
| 170 | + * The pristine tag still carries whatever priority-10 filters did to | |
| 171 | + * it, so only OUR changes are dropped. (#469) | |
| 172 | + * | |
| 173 | + * @param string $tag | |
| 174 | + * @param string $handle | |
| 175 | + * @param string $src | |
| 176 | + */ | |
| 177 | + public static function revert_late_marked_tag( $tag, $handle, $src ): string { | |
| 178 | + if ( ! is_string( $tag ) || '' === $tag || ! self::tag_opts_out( $tag ) ) { | |
| 179 | + return (string) $tag; | |
| 180 | + } | |
| 181 | + $handle = (string) $handle; | |
| 182 | + $pristine = isset( self::$pristine_tag[ $handle ] ) ? self::$pristine_tag[ $handle ] : ''; | |
| 183 | + if ( '' !== $pristine && $pristine !== $tag ) { | |
| 184 | + // The marker is on the tag we were handed, not on the snapshot, | |
| 185 | + // so carry it — and everything else the late filter set in the | |
| 186 | + // same pass — over. A consumer reading the rendered HTML (or | |
| 187 | + // our own buffer passes) must still see the opt-out it asked | |
| 188 | + // for. | |
| 189 | + $tag = self::copy_late_attributes( $tag, $pristine, $handle ); | |
| 190 | + } | |
| 191 | + // The snapshot was taken on `script_loader_tag`, by which point | |
| 192 | + // `script_loader_src` (priority 10) had ALREADY swapped in the | |
| 193 | + // hashed cache URL — so reverting the tag alone still leaves the | |
| 194 | + // minified src behind, which is the half the client actually | |
| 195 | + // reported. Undo that here too, using the URL rewrite_script() | |
| 196 | + // recorded. (#469) | |
| 197 | + return self::restore_marked_script_src( $tag, $handle, self::current_src( $tag, (string) $src ) ); | |
| 198 | + } | |
| 199 | + | |
| 200 | + /** | |
| 201 | + * The src currently on a tag, falling back to the one WordPress passed. | |
| 202 | + * | |
| 203 | + * After a revert the tag carries the snapshot's src, which is not | |
| 204 | + * necessarily the `$src` argument this late in the chain. | |
| 205 | + * | |
| 206 | + * @param string $tag Tag to read. | |
| 207 | + * @param string $fallback Value to use when the tag has no src. | |
| 208 | + */ | |
| 209 | + private static function current_src( string $tag, string $fallback ): string { | |
| 210 | + $open = self::open_tag_offsets( $tag ); | |
| 211 | + if ( null !== $open | |
| 212 | + && preg_match( '#(?<![-\w])src\s*=\s*["\']([^"\']*)["\']#i', $open['attrs'], $m ) ) { | |
| 213 | + return $m[1]; | |
| 214 | + } | |
| 215 | + return $fallback; | |
| 216 | + } | |
| 217 | + | |
| 218 | + /** | |
| 219 | + * Carry the attributes a late filter added onto the snapshot tag. | |
| 220 | + * | |
| 221 | + * Copying only `data-no-*` would silently drop the rest of what the | |
| 222 | + * stamper set in the same pass. Borlabs adds `data-cfasync="false"` | |
| 223 | + * alongside its markers — the attribute that keeps Cloudflare Rocket | |
| 224 | + * Loader off the consent config, i.e. the same class of breakage this | |
| 225 | + * fix exists to prevent, reintroduced by the fix itself. So diff the | |
| 226 | + * attribute names and bring over every one the snapshot lacks. | |
| 227 | + * | |
| 228 | + * Our own transform markers are excluded: they are what we are | |
| 229 | + * reverting, and re-adding `data-xs-delay` would re-delay the script. | |
| 230 | + * | |
| 231 | + * @param string $from Tag as the late filter left it. | |
| 232 | + * @param string $to Snapshot tag to stamp onto. | |
| 233 | + */ | |
| 234 | + private static function copy_late_attributes( string $from, string $to, string $handle ): string { | |
| 235 | + $late_tags = self::open_tags( $from ); | |
| 236 | + $to_tags = self::open_tags( $to ); | |
| 237 | + if ( empty( $late_tags ) || empty( $to_tags ) || count( $late_tags ) !== count( $to_tags ) ) { | |
| 238 | + // Counts differ when a stamper/blocker injected or replaced a | |
| 239 | + // tag inside the concatenated string, or a transform dropped an | |
| 240 | + // inline block. Positional pairing is meaningless then — but | |
| 241 | + // returning the bare snapshot would silently strip the opt-out, | |
| 242 | + // and the buffer passes would re-optimize an unmarked tag: #469 | |
| 243 | + // again, on the mismatch path. Over-marking merely leaves a tag | |
| 244 | + // unoptimized, so stamp the protective attributes onto every | |
| 245 | + // snapshot tag instead. (#470) | |
| 246 | + return self::stamp_protective_attributes( $from, $to, $to_tags ); | |
| 247 | + } | |
| 248 | + // Pair the tags positionally and stamp each one from its own | |
| 249 | + // counterpart. A stamper runs over the whole concatenated string | |
| 250 | + // and may mark several of the tags in it; collapsing that onto one | |
| 251 | + // tag would strip the opt-out from the others, and the buffer | |
| 252 | + // passes re-test `tag_opts_out()` per tag, so an unmarked sibling | |
| 253 | + // is free to be re-optimized downstream — #469 again, one pass | |
| 254 | + // later. (#469) | |
| 255 | + $out = $to; | |
| 256 | + // Right to left: an earlier splice would shift every later offset. | |
| 257 | + for ( $i = count( $to_tags ) - 1; $i >= 0; $i-- ) { | |
| 258 | + $add = self::late_attribute_delta( $late_tags[ $i ]['attrs'], $to_tags[ $i ]['attrs'], $handle ); | |
| 259 | + if ( '' !== $add ) { | |
| 260 | + $out = substr_replace( $out, $add, $to_tags[ $i ]['attrs_end'], 0 ); | |
| 261 | + } | |
| 262 | + } | |
| 263 | + return $out; | |
| 264 | + } | |
| 265 | + | |
| 266 | + /** | |
| 267 | + * Fallback when the late tag and the snapshot cannot be paired | |
| 268 | + * positionally: copy only the attributes that protect the script from | |
| 269 | + * optimizers — the opt-out markers plus `data-cfasync` — onto every | |
| 270 | + * snapshot tag missing them. Values are taken as the stamper wrote | |
| 271 | + * them on the late tag. (#470) | |
| 272 | + * | |
| 273 | + * @param string $from Tag as the late filter left it. | |
| 274 | + * @param string $to Snapshot tag to stamp onto. | |
| 275 | + * @param array $to_tags open_tags() result for $to. | |
| 276 | + */ | |
| 277 | + private static function stamp_protective_attributes( string $from, string $to, array $to_tags ): string { | |
| 278 | + $protect = array(); | |
| 279 | + foreach ( array( 'data-no-optimize', 'data-no-minify', 'data-cfasync' ) as $name ) { | |
| 280 | + if ( preg_match( | |
| 281 | + '#\s(' . preg_quote( $name, '#' ) . ')(\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s>]*))?#i', | |
| 282 | + $from, | |
| 283 | + $m | |
| 284 | + ) ) { | |
| 285 | + $protect[ $name ] = ' ' . $name . ( isset( $m[2] ) ? $m[2] : '' ); | |
| 286 | + } | |
| 287 | + } | |
| 288 | + if ( empty( $protect ) ) { | |
| 289 | + return $to; | |
| 290 | + } | |
| 291 | + $out = $to; | |
| 292 | + // Right to left: an earlier splice would shift every later offset. | |
| 293 | + for ( $i = count( $to_tags ) - 1; $i >= 0; $i-- ) { | |
| 294 | + $add = ''; | |
| 295 | + foreach ( $protect as $name => $attr ) { | |
| 296 | + if ( ! preg_match( '#\s' . preg_quote( $name, '#' ) . '\b#i', $to_tags[ $i ]['attrs'] ) ) { | |
| 297 | + $add .= $attr; | |
| 298 | + } | |
| 299 | + } | |
| 300 | + if ( '' !== $add ) { | |
| 301 | + $out = substr_replace( $out, $add, $to_tags[ $i ]['attrs_end'], 0 ); | |
| 302 | + } | |
| 303 | + } | |
| 304 | + return $out; | |
| 305 | + } | |
| 306 | + | |
| 307 | + /** | |
| 308 | + * The attributes present on the late tag but not the snapshot, minus | |
| 309 | + * the ones OUR transforms put there for this handle. | |
| 310 | + * | |
| 311 | + * Only attributes recorded in $our_late_attrs are dropped — a blanket | |
| 312 | + * defer/type skip threw away a defer the STAMPER set in the same pass | |
| 313 | + * as its marker. Themify prints main.js with defer + data-no-optimize | |
| 314 | + * together, and its config rides a deferred data: URI script printed | |
| 315 | + * just before it; stripping the theme's defer made main.js | |
| 316 | + * parser-blocking, so it ran ahead of its config and the theme died | |
| 317 | + * with "themify_vars is not defined". `src` is still never copied: | |
| 318 | + * it belongs to the snapshot, and restore_marked_script_src() owns | |
| 319 | + * undoing a minified URL. | |
| 320 | + * | |
| 321 | + * @param string $late_attrs Attribute string from the transformed tag. | |
| 322 | + * @param string $to_attrs Attribute string from the snapshot tag. | |
| 323 | + * @param string $handle Script handle the tags belong to. | |
| 324 | + */ | |
| 325 | + private static function late_attribute_delta( string $late_attrs, string $to_attrs, string $handle ): string { | |
| 326 | + $pattern = '#\s([-\w:]+)(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s>]*))?#'; | |
| 327 | + if ( ! preg_match_all( $pattern, $late_attrs, $late, PREG_SET_ORDER ) ) { | |
| 328 | + return ''; | |
| 329 | + } | |
| 330 | + $have = array(); | |
| 331 | + if ( preg_match_all( $pattern, $to_attrs, $existing, PREG_SET_ORDER ) ) { | |
| 332 | + foreach ( $existing as $attr ) { | |
| 333 | + $have[ strtolower( $attr[1] ) ] = true; | |
| 334 | + } | |
| 335 | + } | |
| 336 | + $add = ''; | |
| 337 | + foreach ( $late as $attr ) { | |
| 338 | + $name = strtolower( $attr[1] ); | |
| 339 | + if ( isset( $have[ $name ] ) || 'src' === $name || isset( self::$our_late_attrs[ $handle ][ $name ] ) ) { | |
| 340 | + continue; | |
| 341 | + } | |
| 342 | + if ( 0 === strpos( $name, 'data-xs-' ) ) { | |
| 343 | + continue; | |
| 344 | + } | |
| 345 | + $add .= $attr[0]; | |
| 346 | + } | |
| 347 | + return $add; | |
| 348 | + } | |
| 349 | + | |
| 350 | + /** | |
| 351 | + * Attribute names OUR transforms added in this request, keyed by | |
| 352 | + * handle: defer_script_tag() records `defer`, delay_script_tag() | |
| 353 | + * records `type` when it parks an inline block. Copying one of these | |
| 354 | + * from the late tag back onto the snapshot would re-apply the very | |
| 355 | + * transform the revert is undoing — but the same names coming from a | |
| 356 | + * STAMPER are the author's intent and must survive, so the skip is | |
| 357 | + * per-handle, never by name alone. `data-xs-*` is handled by prefix | |
| 358 | + * separately. (#469) | |
| 359 | + * | |
| 360 | + * @var array<string,array<string,true>> | |
| 361 | + */ | |
| 362 | + private static $our_late_attrs = array(); | |
| 363 | + | |
| 364 | + /** | |
| 365 | + * Locate the opening `<script>` that carries the src, falling back to | |
| 366 | + * the last one when none does. | |
| 367 | + * | |
| 368 | + * WP_Scripts::do_item() hands `script_loader_tag` the concatenation of | |
| 369 | + * before_inline + external + after_inline, so the FIRST `<script` is | |
| 370 | + * routinely an inline block rather than the asset — the same trap | |
| 371 | + * #234 fixed for defer and #273 for delay. Scanning attribute-wise | |
| 372 | + * also means a quoted value containing `>` (an `onerror` guard, a JSON | |
| 373 | + * payload) cannot truncate the tag the way `[^>]*` did. (#469) | |
| 374 | + * | |
| 375 | + * @param string $tag Full tag string. | |
| 376 | + * @return array{attrs:string,attrs_end:int}|null | |
| 377 | + */ | |
| 378 | + private static function open_tag_offsets( string $tag ): ?array { | |
| 379 | + $tags = self::open_tags( $tag ); | |
| 380 | + $fallback = null; | |
| 381 | + foreach ( $tags as $found ) { | |
| 382 | + if ( preg_match( '#(?<![-\w])src\s*=#i', $found['attrs'] ) ) { | |
| 383 | + return $found; | |
| 384 | + } | |
| 385 | + $fallback = $found; | |
| 386 | + } | |
| 387 | + return $fallback; | |
| 388 | + } | |
| 389 | + | |
| 390 | + /** | |
| 391 | + * Every well-formed opening `<script>` in the string, in order. | |
| 392 | + * | |
| 393 | + * @param string $tag Full tag string. | |
| 394 | + * @return array<int,array{attrs:string,attrs_end:int}> | |
| 395 | + */ | |
| 396 | + private static function open_tags( string $tag ): array { | |
| 397 | + if ( ! preg_match_all( '#<script\b#i', $tag, $m, PREG_OFFSET_CAPTURE ) ) { | |
| 398 | + return array(); | |
| 399 | + } | |
| 400 | + $found = array(); | |
| 401 | + foreach ( $m[0] as $hit ) { | |
| 402 | + $start = (int) $hit[1] + strlen( $hit[0] ); | |
| 403 | + $end = self::scan_open_tag_end( $tag, $start ); | |
| 404 | + if ( null === $end ) { | |
| 405 | + continue; | |
| 406 | + } | |
| 407 | + $found[] = array( | |
| 408 | + 'attrs' => substr( $tag, $start, $end - $start ), | |
| 409 | + 'attrs_end' => $end, | |
| 410 | + ); | |
| 411 | + } | |
| 412 | + return $found; | |
| 413 | + } | |
| 414 | + | |
| 415 | + /** | |
| 416 | + * Offset of the `>` closing an opening tag, skipping any that sit | |
| 417 | + * inside a quoted attribute value. Null when the tag is unterminated. | |
| 418 | + * | |
| 419 | + * @param string $tag Full tag string. | |
| 420 | + * @param int $offset Index just past `<script`. | |
| 421 | + */ | |
| 422 | + private static function scan_open_tag_end( string $tag, int $offset ): ?int { | |
| 423 | + $len = strlen( $tag ); | |
| 424 | + $quote = ''; | |
| 425 | + for ( $i = $offset; $i < $len; $i++ ) { | |
| 426 | + $char = $tag[ $i ]; | |
| 427 | + if ( '' !== $quote ) { | |
| 428 | + if ( $char === $quote ) { | |
| 429 | + $quote = ''; | |
| 430 | + } | |
| 431 | + continue; | |
| 432 | + } | |
| 433 | + if ( '"' === $char || "'" === $char ) { | |
| 434 | + $quote = $char; | |
| 435 | + continue; | |
| 436 | + } | |
| 437 | + if ( '>' === $char ) { | |
| 438 | + // A self-closing `/>` keeps the slash out of the attributes. | |
| 439 | + return ( $i > $offset && '/' === $tag[ $i - 1 ] ) ? $i - 1 : $i; | |
| 440 | + } | |
| 441 | + } | |
| 442 | + return null; | |
| 443 | + } | |
| 444 | + | |
| 445 | + /** | |
| 446 | + * Filter: `script_loader_tag`, priority 15 — undo the minify-cache | |
| 447 | + * rewrite for a script whose printed tag opts out. | |
| 448 | + * | |
| 449 | + * The src rewrite happens on `script_loader_src` (priority 10), long | |
| 450 | + * before any plugin's own `script_loader_tag` filter can stamp | |
| 451 | + * `data-no-minify` onto the tag — so the marker arrived too late to | |
| 452 | + * prevent the rewrite. This runs after the filters that stamp at the | |
| 453 | + * default priority 10 and swaps the hashed cache URL back to the | |
| 454 | + * recorded original. A marker stamped later than our transforms is | |
| 455 | + * caught by revert_late_marked_tag() in the late pass instead. (#469) | |
| 456 | + * | |
| 457 | + * @param string $tag | |
| 458 | + * @param string $handle | |
| 459 | + * @param string $src | |
| 460 | + */ | |
| 461 | + public static function restore_marked_script_src( $tag, $handle, $src ): string { | |
| 462 | + if ( ! is_string( $tag ) || '' === $tag || ! self::tag_opts_out( $tag ) ) { | |
| 463 | + return (string) $tag; | |
| 464 | + } | |
| 465 | + $original = self::original_src( (string) $handle ); | |
| 466 | + if ( '' === $original || '' === (string) $src || false === strpos( $tag, (string) $src ) ) { | |
| 467 | + return $tag; | |
| 468 | + } | |
| 469 | + return str_replace( (string) $src, $original, $tag ); | |
| 470 | + } | |
| 471 | + | |
| 472 | + /** | |
| 86 | 473 | * Does a user-supplied target match this script? |
| 87 | 474 | * |
| 88 | 475 | * A target is either a script handle (exact) or a URL substring. The |
| 89 | 476 | * URL is checked against BOTH the current src and the pre-minify src, |
| @@ -132,8 +519,12 @@ | ||
| 132 | 519 | // bundle's <script> tag intact so the dashboard mounts. |
| 133 | 520 | if ( self::skip_in_non_frontend_context() ) { |
| 134 | 521 | return $tag; |
| 135 | 522 | } |
| 523 | + // The author asked every optimizer to leave this tag alone. | |
| 524 | + if ( self::carries_optimizer_opt_out( $tag ) ) { | |
| 525 | + return $tag; | |
| 526 | + } | |
| 136 | 527 | if ( '' === (string) $src ) { |
| 137 | 528 | return $tag; |
| 138 | 529 | } |
| 139 | 530 | if ( self::is_excluded_script( (string) $handle, (string) $src ) ) { |
| @@ -138,8 +529,12 @@ | ||
| 138 | 529 | } |
| 139 | 530 | if ( self::is_excluded_script( (string) $handle, (string) $src ) ) { |
| 140 | 531 | return $tag; |
| 141 | 532 | } |
| 533 | + // The tag itself asked to be left alone. (#456) | |
| 534 | + if ( self::tag_opts_out( $tag ) ) { | |
| 535 | + return $tag; | |
| 536 | + } | |
| 142 | 537 | // Inline code elsewhere on the page reads this handle (or something |
| 143 | 538 | // it depends on). Inline blocks never defer, so deferring this one |
| 144 | 539 | // would run the consumer first. Defer only — delay is an opt-in |
| 145 | 540 | // target list, where the user has named the script deliberately. |
| @@ -163,9 +558,15 @@ | ||
| 163 | 558 | // dependent that touches a global its dependency defines. (#234) |
| 164 | 559 | // |
| 165 | 560 | // The lookahead scans only within the tag (`[^>]*`) for ` src=`, so |
| 166 | 561 | // an inline `<script id="…-js-before">` can never match. |
| 167 | - return (string) preg_replace( '#<script\b(?=[^>]*\ssrc\s*=)#i', '<script defer="defer"', $tag, 1 ); | |
| 562 | + $deferred = (string) preg_replace( '#<script\b(?=[^>]*\ssrc\s*=)#i', '<script defer="defer"', $tag, 1 ); | |
| 563 | + if ( $deferred !== $tag ) { | |
| 564 | + // Remember that THIS defer is ours, so the late opt-out revert | |
| 565 | + // drops it — and only it, never a stamper's own defer. | |
| 566 | + self::$our_late_attrs[ (string) $handle ]['defer'] = true; | |
| 567 | + } | |
| 568 | + return $deferred; | |
| 168 | 569 | } |
| 169 | 570 | |
| 170 | 571 | /** |
| 171 | 572 | * Filter: `script_loader_tag` — rewrite src= to data-xs-src= so the |
| @@ -184,11 +585,19 @@ | ||
| 184 | 585 | } |
| 185 | 586 | if ( self::skip_in_non_frontend_context() ) { |
| 186 | 587 | return $tag; |
| 187 | 588 | } |
| 188 | - if ( self::is_excluded_script( (string) $handle, (string) $src ) ) { | |
| 589 | + // The author asked every optimizer to leave this tag alone. | |
| 590 | + if ( self::carries_optimizer_opt_out( $tag ) ) { | |
| 189 | 591 | return $tag; |
| 190 | 592 | } |
| 593 | + if ( self::is_excluded_script( (string) $handle, (string) $src, true ) ) { | |
| 594 | + return $tag; | |
| 595 | + } | |
| 596 | + // The tag itself asked to be left alone. (#456) | |
| 597 | + if ( self::tag_opts_out( $tag ) ) { | |
| 598 | + return $tag; | |
| 599 | + } | |
| 191 | 600 | if ( ! self::is_delay_target( (string) $handle, (string) $src ) ) { |
| 192 | 601 | return $tag; |
| 193 | 602 | } |
| 194 | 603 | // Inline code elsewhere on the page reads this handle (or something |
| @@ -199,9 +608,16 @@ | ||
| 199 | 608 | // the moment jquery-core is delayed. A handle the user NAMED in |
| 200 | 609 | // delay_js_targets is still delayed — an explicit entry is the user |
| 201 | 610 | // saying they know the inline consumer is safe to break or absent. |
| 202 | 611 | if ( isset( self::inline_bound_handles()[ (string) $handle ] ) |
| 203 | - && ! self::is_user_named_target( (string) $handle, (string) $src ) ) { | |
| 612 | + && ! self::is_user_named_target( (string) $handle, (string) $src ) | |
| 613 | + // Smart Delay inverts this protection: the handle is delayed and | |
| 614 | + // its own before/after snippets are parked WITH it (see | |
| 615 | + // park_smart_inline()), so the consumer no longer runs against a | |
| 616 | + // missing global — it replays after its provider, in page order. | |
| 617 | + // On a builder page nearly every script is inline-bound, which is | |
| 618 | + // why delay-all without this delayed almost nothing. | |
| 619 | + && ! self::smart_delay_enabled() ) { | |
| 204 | 620 | return $tag; |
| 205 | 621 | } |
| 206 | 622 | // A non-executable type means this tag is data, or is being held by |
| 207 | 623 | // somebody else on purpose. The buffer pass has always checked this; |
| @@ -244,9 +660,9 @@ | ||
| 244 | 660 | // would win over a marker appended behind it and keep executing. |
| 245 | 661 | // A non-default original type is stashed in data-xs-type so the |
| 246 | 662 | // bootstrap can restore it on replay (#274 — type is what a script |
| 247 | 663 | // IS; a parked `type="module"` must come back as a module). |
| 248 | - $tag = (string) preg_replace_callback( | |
| 664 | + $parked = (string) preg_replace_callback( | |
| 249 | 665 | '#<script\b([^>]*)>#i', |
| 250 | 666 | static function ( array $m ): string { |
| 251 | 667 | return '<script' . self::park_type_attrs( $m[1] ) . '>'; |
| 252 | 668 | }, |
| @@ -252,9 +668,14 @@ | ||
| 252 | 668 | }, |
| 253 | 669 | $tag, |
| 254 | 670 | 1 |
| 255 | 671 | ); |
| 256 | - return $tag; | |
| 672 | + if ( $parked !== $tag ) { | |
| 673 | + // The parked type is ours to drop on a late opt-out revert; an | |
| 674 | + // author-set type sits on the snapshot and survives regardless. | |
| 675 | + self::$our_late_attrs[ (string) $handle ]['type'] = true; | |
| 676 | + } | |
| 677 | + return $parked; | |
| 257 | 678 | } |
| 258 | 679 | |
| 259 | 680 | /** |
| 260 | 681 | * Script types the buffer pass must never touch. `<script>` carries |
| @@ -262,8 +683,104 @@ | ||
| 262 | 683 | * consumers, importmaps must resolve before any module runs, and our |
| 263 | 684 | * own delayed-inline marker is already handled by the bootstrap. |
| 264 | 685 | * Rewriting any of these breaks the page or its metadata. |
| 265 | 686 | */ |
| 687 | + /** | |
| 688 | + * Attributes by which a script's own author tells optimizers to stand down. | |
| 689 | + * | |
| 690 | + * The report behind #275 also asked us to leave a script alone when its | |
| 691 | + * author "already marked it to load late". Read literally that means | |
| 692 | + * `defer`/`async`, and that reading is wrong twice over: `defer` is | |
| 693 | + * stamped onto every enqueued script by our OWN Defer JS filter at | |
| 694 | + * priority 20, before Delay JS sees it at 30 — so honouring it would | |
| 695 | + * switch Delay JS off entirely on sites running both — and `async` is the | |
| 696 | + * shape of gtag, GTM and every pixel loader, which is precisely the | |
| 697 | + * payload Delay JS exists to postpone. `defer`/`async` say WHEN TO FETCH, | |
| 698 | + * not "leave me alone". | |
| 699 | + * | |
| 700 | + * These attributes do say it. Each is an established opt-out honoured by | |
| 701 | + * another optimizer — WP Rocket, LiteSpeed, Autoptimize, NitroPack, | |
| 702 | + * Jetpack Boost — so an author who prints one has already declared that | |
| 703 | + * no optimizer should touch this tag. Consent banners are the main | |
| 704 | + * beneficiary, but the rule is general and needs neither a handle nor a | |
| 705 | + * recognised URL, so it works identically on both passes. | |
| 706 | + * | |
| 707 | + * Two deliberate omissions: | |
| 708 | + * | |
| 709 | + * - `data-cfasync="false"` is a Cloudflare Rocket Loader opt-out, and | |
| 710 | + * ad stacks (Mediavine, Ezoic, AdThrive) print it on exactly the | |
| 711 | + * heavy loaders a site turns Delay JS on for. Honouring it would | |
| 712 | + * un-delay the ads. | |
| 713 | + * - `data-no-minify` is about minification, not execution timing. | |
| 714 | + */ | |
| 715 | + private const OPT_OUT_ATTRIBUTES = array( | |
| 716 | + 'nowprocket', // WP Rocket | |
| 717 | + 'data-nowprocket', // WP Rocket | |
| 718 | + 'data-no-optimize', // LiteSpeed | |
| 719 | + 'data-noptimize', // Autoptimize | |
| 720 | + 'data-no-defer', // used by several optimizers | |
| 721 | + 'nitro-exclude', // NitroPack | |
| 722 | + 'data-jetpack-boost', // Jetpack Boost (value "ignore") | |
| 723 | + 'data-wpmeteor-nooptimize', // WP Meteor | |
| 724 | + 'data-xs-nodelay', // ours | |
| 725 | + ); | |
| 726 | + | |
| 727 | + /** | |
| 728 | + * Does this tag carry an explicit "optimizers keep out" attribute? | |
| 729 | + * | |
| 730 | + * Same `(?<![-\w])` lookbehind the rest of this file uses, so | |
| 731 | + * `data-nowprocket` does not also satisfy a bare `nowprocket` lookup, and | |
| 732 | + * a trailing `\b` so `data-no-defer` does not match `data-no-deferral`. | |
| 733 | + * Bare and valued forms both count: an author writes `nowprocket`, | |
| 734 | + * `nowprocket=""` and `data-noptimize="1"` interchangeably. | |
| 735 | + * | |
| 736 | + * @param string $tag Full opening tag. | |
| 737 | + */ | |
| 738 | + private static function carries_optimizer_opt_out( string $tag ): bool { | |
| 739 | + // Read ATTRIBUTE NAMES, not the tag as a string. A substring scan | |
| 740 | + // matched `src="https://cdn/nowprocket/loader.js"`, `?nowprocket=1`, | |
| 741 | + // `class="nowprocket"` and any inline body that merely mentioned one | |
| 742 | + // of these names -- each silently un-delaying a script that should | |
| 743 | + // have been delayed. | |
| 744 | + // | |
| 745 | + // EVERY opening tag is checked, not just the first. On the enqueue | |
| 746 | + // path WP_Scripts::do_item() hands us translations + before-inline + | |
| 747 | + // the real tag + after-inline concatenated, so the first `<script` | |
| 748 | + // is often an inline block and the author's opt-out sits on the | |
| 749 | + // external tag behind it. Reading only the first tag missed it and | |
| 750 | + // delayed the script anyway -- the wrong direction: a consent banner | |
| 751 | + // its author told optimizers to leave alone would not appear. | |
| 752 | + // | |
| 753 | + // The tag regex is quote-aware because `[^>]*>` stops at a `>` inside | |
| 754 | + // a quoted value, and consent managers routinely ship JSON in a | |
| 755 | + // data-* attribute. | |
| 756 | + if ( ! preg_match_all( '#<script\b(?:[^>"\']|"[^"]*"|\'[^\']*\')*>#is', $tag, $tags ) ) { | |
| 757 | + return false; | |
| 758 | + } | |
| 759 | + | |
| 760 | + foreach ( $tags[0] as $open ) { | |
| 761 | + // Walk name/value pairs. The name pattern is deliberately | |
| 762 | + // permissive: a name we cannot recognise (Alpine's `@load`, say) | |
| 763 | + // must still consume ITS OWN VALUE, or the value gets scanned as | |
| 764 | + // if it were more attribute names. | |
| 765 | + if ( ! preg_match_all( | |
| 766 | + '#\s+([^\s=/>]+)(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s>]*))?#s', | |
| 767 | + substr( $open, 7, -1 ), | |
| 768 | + $found | |
| 769 | + ) ) { | |
| 770 | + continue; | |
| 771 | + } | |
| 772 | + | |
| 773 | + foreach ( $found[1] as $name ) { | |
| 774 | + if ( in_array( strtolower( $name ), self::OPT_OUT_ATTRIBUTES, true ) ) { | |
| 775 | + return true; | |
| 776 | + } | |
| 777 | + } | |
| 778 | + } | |
| 779 | + | |
| 780 | + return false; | |
| 781 | + } | |
| 782 | + | |
| 266 | 783 | private const NON_EXECUTABLE_TYPES = array( |
| 267 | 784 | 'application/ld+json', |
| 268 | 785 | 'application/json', |
| 269 | 786 | 'importmap', |
| @@ -397,8 +914,24 @@ | ||
| 397 | 914 | if ( false !== stripos( $tag, 'data-xs-delay' ) || false !== stripos( $tag, 'data-xs-src' ) ) { |
| 398 | 915 | return $tag; |
| 399 | 916 | } |
| 400 | 917 | |
| 918 | + // The author asked every optimizer to leave this tag alone. | |
| 919 | + // Checked before src/type: it needs neither, so an | |
| 920 | + // un-enqueued banner printed straight into wp_head is | |
| 921 | + // covered the same as an enqueued one. | |
| 922 | + // | |
| 923 | + // Both checks, because they disagree on purpose and either | |
| 924 | + // saying "leave it" is the safe answer. tag_opts_out() is | |
| 925 | + // dev's (#456) and also drives the late re-check at #469; | |
| 926 | + // carries_optimizer_opt_out() reads attribute NAMES across | |
| 927 | + // every opening tag, so it is not fooled by a marker sitting | |
| 928 | + // inside a quoted value or an inline body, and it knows the | |
| 929 | + // other optimizers' markers. | |
| 930 | + if ( self::tag_opts_out( $tag ) || self::carries_optimizer_opt_out( $tag ) ) { | |
| 931 | + return $tag; | |
| 932 | + } | |
| 933 | + | |
| 401 | 934 | // No src → inline code. The enqueue path owns those; a |
| 402 | 935 | // buffer rewrite here would have to reason about execution |
| 403 | 936 | // order it cannot see. |
| 404 | 937 | // `(?<![-\w])` not `\b` — see the note on the enqueue-path |
| @@ -421,37 +954,48 @@ | ||
| 421 | 954 | return $tag; |
| 422 | 955 | } |
| 423 | 956 | } |
| 424 | 957 | |
| 425 | - // Recover the handle from the tag's id before deciding. | |
| 958 | + // An ENQUEUED script reaches this sweep too: the enqueue-path | |
| 959 | + // filter leaves an EXCLUDED tag unmarked, and unmarked is all | |
| 960 | + // this pass can see. Judging it on its URL alone re-delays the | |
| 961 | + // very script the exclusion protected — and a handle is not | |
| 962 | + // generally in its own URL, which is the shape Complianz | |
| 963 | + // (`cmplz-cookiebanner`), NotificationX (`notificationx-public`) | |
| 964 | + // and jQuery (`jquery-core`) all have. A site with jquery-core | |
| 965 | + // excluded still shipped jQuery delayed, and every inline | |
| 966 | + // `jQuery(...)` on the page threw "jQuery is not defined". | |
| 967 | + // WordPress prints `id="<handle>-js"` on every enqueued | |
| 968 | + // script, so the handle is right there in the tag. (#275) | |
| 426 | 969 | // |
| 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. | |
| 970 | + // The lookbehind matters: `data-id="cmplz-cookiebanner-js"` is | |
| 971 | + // somebody's own attribute, not the handle, and reading it as | |
| 972 | + // one would shield a script nobody excluded. | |
| 437 | 973 | // |
| 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. | |
| 974 | + // Merge note for #374: if a URL->handle map built from | |
| 975 | + // wp_scripts() lands first, resolve through that and keep | |
| 976 | + // this as the FALLBACK rather than replacing it. The map is | |
| 977 | + // keyed on the REGISTERED src, and Minifier::rewrite_script() | |
| 978 | + // rewrites a local script's URL to a hashed /cache/xspeed/min/ | |
| 979 | + // path at output time -- which is why remember_original_src() | |
| 980 | + // exists. So with minify_js on, the map misses every minified | |
| 981 | + // script and an excluded one would be re-delayed here. The | |
| 982 | + // `id` survives that rewrite. | |
| 444 | 983 | $tag_handle = ''; |
| 445 | - if ( preg_match( '#\sid\s*=\s*(["\'])(.*?)\1#i', $tag, $id_m ) ) { | |
| 984 | + if ( preg_match( '#(?<![-\w])id\s*=\s*(["\'])(.*?)\1#is', $tag, $id_m ) ) { | |
| 446 | 985 | // WP appends `-js`; anything else is somebody's own id and |
| 447 | 986 | // is still worth matching literally. |
| 448 | - $tag_handle = (string) preg_replace( '/-js$/', '', $id_m[2] ); | |
| 987 | + $tag_handle = (string) preg_replace( '/-js$/', '', trim( $id_m[2] ) ); | |
| 449 | 988 | } |
| 450 | 989 | |
| 451 | - if ( self::is_excluded_script( $tag_handle, $src ) ) { | |
| 990 | + if ( self::is_excluded_script( $tag_handle, $src, true ) ) { | |
| 452 | 991 | return $tag; |
| 453 | 992 | } |
| 993 | + // The handle is passed to the target test as well, so naming a | |
| 994 | + // handle in the delay list behaves the same here as it does on | |
| 995 | + // the enqueue path. The two layers disagreeing on what a target | |
| 996 | + // means is what made this look like a matching quirk rather | |
| 997 | + // than a whole layer ignoring the list. | |
| 454 | 998 | if ( ! self::is_delay_target( $tag_handle, $src ) ) { |
| 455 | 999 | return $tag; |
| 456 | 1000 | } |
| 457 | 1001 | // Mirror of the enqueue-path guard: a handle that inline code |
| @@ -513,11 +1057,13 @@ | ||
| 513 | 1057 | if ( empty( $opts['delay_js'] ) ) { |
| 514 | 1058 | return $html; |
| 515 | 1059 | } |
| 516 | 1060 | |
| 1061 | + $handle_delayed = self::handle_delay_outcomes( $html ); | |
| 1062 | + | |
| 517 | 1063 | $out = preg_replace_callback( |
| 518 | 1064 | '#<script\b([^>]*)>(.*?)</script>#is', |
| 519 | - static function ( array $m ): string { | |
| 1065 | + static function ( array $m ) use ( $handle_delayed ): string { | |
| 520 | 1066 | list( $whole, $attrs, $body ) = $m; |
| 521 | 1067 | |
| 522 | 1068 | if ( '' === trim( $body ) ) { |
| 523 | 1069 | return $whole; |
| @@ -522,8 +1068,13 @@ | ||
| 522 | 1068 | if ( '' === trim( $body ) ) { |
| 523 | 1069 | return $whole; |
| 524 | 1070 | } |
| 525 | 1071 | |
| 1072 | + // The tag itself asked to be left alone. (#456) | |
| 1073 | + if ( self::tag_opts_out( $attrs ) ) { | |
| 1074 | + return $whole; | |
| 1075 | + } | |
| 1076 | + | |
| 526 | 1077 | // Our own replay bootstrap. Its body quotes the delay |
| 527 | 1078 | // machinery's own strings, so a pathological user target |
| 528 | 1079 | // fragment could match it — and a parked bootstrap means |
| 529 | 1080 | // nothing on the page ever replays. |
| @@ -551,8 +1102,47 @@ | ||
| 551 | 1102 | if ( false !== stripos( $body, 'document.write' ) ) { |
| 552 | 1103 | return $whole; |
| 553 | 1104 | } |
| 554 | 1105 | |
| 1106 | + // Our own inline scripts, by the id they are printed with. | |
| 1107 | + // The src passes get this for free from the handle prefix, | |
| 1108 | + // but here the handle is '' — and the facade observer's body | |
| 1109 | + // names youtube/vimeo, so a user target like "youtube" would | |
| 1110 | + // park the very script that makes those embeds cheap. | |
| 1111 | + if ( preg_match( '#(?<![-\w])id\s*=\s*(["\'])xspeed-#i', $attrs ) ) { | |
| 1112 | + return $whole; | |
| 1113 | + } | |
| 1114 | + | |
| 1115 | + // A handle's own inline blocks follow the handle, not only their | |
| 1116 | + // body text. The body rule below decided them alone, so a | |
| 1117 | + // `-js-extra` whose data named a target was parked while its | |
| 1118 | + // script, kept eager by a URL exclusion, ran first and read an | |
| 1119 | + // undefined global. (#549) | |
| 1120 | + // | |
| 1121 | + // Ahead of the exclusion list on purpose. The handle's own tag | |
| 1122 | + // was already weighed against it by handle and URL; a body | |
| 1123 | + // match here would keep the after-code of a delayed script | |
| 1124 | + // eager, running it before the script it calls. | |
| 1125 | + if ( preg_match( '#(?<![-\w])id\s*=\s*(["\'])(.+?)-js-(extra|before|after)\1#i', $attrs, $own ) ) { | |
| 1126 | + $part = strtolower( $own[3] ); | |
| 1127 | + // wp_localize_script data. Early is always safe: it only | |
| 1128 | + // assigns, and its script cannot run before it. | |
| 1129 | + if ( 'extra' === $part ) { | |
| 1130 | + return $whole; | |
| 1131 | + } | |
| 1132 | + if ( isset( $handle_delayed[ $own[2] ] ) ) { | |
| 1133 | + if ( $handle_delayed[ $own[2] ] ) { | |
| 1134 | + return '<script' . self::park_type_attrs( $attrs ) . '>' . $body . '</script>'; | |
| 1135 | + } | |
| 1136 | + // The script runs at load, so its `before` code must too. | |
| 1137 | + // Its `after` code still runs after it if parked, so that | |
| 1138 | + // one is left to the body rule, like any vendor loader. | |
| 1139 | + if ( 'before' === $part ) { | |
| 1140 | + return $whole; | |
| 1141 | + } | |
| 1142 | + } | |
| 1143 | + } | |
| 1144 | + | |
| 555 | 1145 | // The body stands in for the URL in the lists the src passes |
| 556 | 1146 | // consult — but NOT via is_delay_target(), whose empty-list |
| 557 | 1147 | // default is "delay everything". That default is right for a |
| 558 | 1148 | // tag with a URL and catastrophic here: it would park every |
| @@ -558,12 +1148,16 @@ | ||
| 558 | 1148 | // tag with a URL and catastrophic here: it would park every |
| 559 | 1149 | // inline script on the page. Inline code is delayed only on a |
| 560 | 1150 | // positive identification — the body names a known vendor |
| 561 | 1151 | // host, or a fragment the user targeted — and the exclusion |
| 562 | - // list still wins first. | |
| 563 | - if ( self::is_excluded_script( '', $body ) ) { | |
| 1152 | + // list still wins first. A target naming a consent manager | |
| 1153 | + // lifts the floor here the same way it does for a src tag; | |
| 1154 | + // without it the same entry delayed the file and left the | |
| 1155 | + // vendor's inline code eager. | |
| 1156 | + if ( self::is_excluded_script( '', $body, true ) ) { | |
| 564 | 1157 | return $whole; |
| 565 | 1158 | } |
| 1159 | + | |
| 566 | 1160 | if ( ! self::matches_known_third_party( $body ) && ! self::matches_user_targets( $body ) ) { |
| 567 | 1161 | return $whole; |
| 568 | 1162 | } |
| 569 | 1163 | |
| @@ -582,8 +1176,33 @@ | ||
| 582 | 1176 | return null === $out ? $html : $out; |
| 583 | 1177 | } |
| 584 | 1178 | |
| 585 | 1179 | /** |
| 1180 | + * Whether each enqueued handle's external tag ended up delayed. | |
| 1181 | + * | |
| 1182 | + * Read from the finished HTML rather than recorded as tags are filtered: | |
| 1183 | + * this runs after every pass that can delay a tag (script_loader_tag, the | |
| 1184 | + * late opt-out revert, the raw-tag sweep), so the page itself is the only | |
| 1185 | + * complete answer. | |
| 1186 | + * | |
| 1187 | + * @param string $html Complete page HTML. | |
| 1188 | + * @return array<string,bool> Handle => delayed. | |
| 1189 | + */ | |
| 1190 | + private static function handle_delay_outcomes( string $html ): array { | |
| 1191 | + if ( ! preg_match_all( '#<script\b((?:"[^"]*"|\'[^\']*\'|[^>"\'])*)>#i', $html, $m ) ) { | |
| 1192 | + return array(); | |
| 1193 | + } | |
| 1194 | + $out = array(); | |
| 1195 | + foreach ( $m[1] as $attrs ) { | |
| 1196 | + if ( ! preg_match( '#(?<![-\w])id\s*=\s*(["\'])(.+?)-js\1#i', $attrs, $id ) ) { | |
| 1197 | + continue; | |
| 1198 | + } | |
| 1199 | + $out[ $id[2] ] = false !== stripos( $attrs, 'data-xs-delay' ) || false !== stripos( $attrs, 'data-xs-src' ); | |
| 1200 | + } | |
| 1201 | + return $out; | |
| 1202 | + } | |
| 1203 | + | |
| 1204 | + /** | |
| 586 | 1205 | * Inline bootstrap that flips delayed scripts on the first user |
| 587 | 1206 | * interaction. Printed once on wp_footer priority 1000. |
| 588 | 1207 | */ |
| 589 | 1208 | public static function print_delay_bootstrap(): void { |
| @@ -603,70 +1222,49 @@ | ||
| 603 | 1222 | $opts = self::opts(); |
| 604 | 1223 | $timeout = isset( $opts['delay_js_timeout'] ) ? (int) $opts['delay_js_timeout'] : 8000; |
| 605 | 1224 | $timeout = max( 0, min( 60000, $timeout ) ); |
| 606 | 1225 | |
| 607 | - // Tiny vanilla bootstrap; keep it self-contained so the page | |
| 608 | - // has no JS dependencies before the first interaction. | |
| 609 | - ?> | |
| 610 | -<script id="xspeed-delay-bootstrap"> | |
| 611 | -(function(){ | |
| 612 | - var events=['mousemove','keydown','touchstart','scroll','wheel']; | |
| 613 | - var fired=false; | |
| 614 | - function load(){ | |
| 615 | - if(fired)return;fired=true; | |
| 616 | - events.forEach(function(e){window.removeEventListener(e,load,{passive:true,capture:true});}); | |
| 617 | - var delayed=document.querySelectorAll('script[data-xs-delay]'); | |
| 618 | - delayed.forEach(function(s){ | |
| 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;} | |
| 634 | - Array.prototype.slice.call(s.attributes).forEach(function(a){ | |
| 635 | - if(a.name==='data-xs-src'){n.setAttribute('src',a.value);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; | |
| 653 | - n.setAttribute(a.name,a.value); | |
| 654 | - }); | |
| 655 | - if(!s.hasAttribute('data-xs-src')){n.text=s.text;} | |
| 656 | - s.parentNode.replaceChild(n,s); | |
| 657 | - }); | |
| 658 | - } | |
| 659 | - events.forEach(function(e){window.addEventListener(e,load,{passive:true,capture:true});}); | |
| 660 | -<?php if ( $timeout > 0 ) : ?> | |
| 661 | - setTimeout(load,<?php echo (int) $timeout; ?>); | |
| 662 | -<?php endif; ?> | |
| 663 | -})(); | |
| 664 | -</script> | |
| 665 | - <?php | |
| 1226 | + // The script is includes/js/delay-bootstrap.js, which also carries | |
| 1227 | + // the design notes for the lifecycle replay (#494). `npm run build` | |
| 1228 | + // minifies it into assets/delay-bootstrap.min.js; the timeout goes in | |
| 1229 | + // place of its one placeholder. | |
| 1230 | + // | |
| 1231 | + // The tag goes out through wp_print_inline_script_tag(), like Free's | |
| 1232 | + // other inline scripts, so a CSP plugin's wp_inline_script_attributes | |
| 1233 | + // filter can give it a nonce. Printed bare, a nonce CSP blocked it | |
| 1234 | + // and nothing was ever replayed. | |
| 1235 | + $js = str_replace( 'XSPEED_DELAY_TIMEOUT', (string) $timeout, self::delay_bootstrap_js() ); | |
| 1236 | + wp_print_inline_script_tag( $js, array( 'id' => 'xspeed-delay-bootstrap' ) ); | |
| 666 | 1237 | } |
| 667 | 1238 | |
| 1239 | + /** The delay bootstrap's code, read once per request. */ | |
| 1240 | + private static $delay_bootstrap_js = null; | |
| 1241 | + | |
| 668 | 1242 | /** |
| 1243 | + * The built delay bootstrap, without the line that records its source. | |
| 1244 | + * If the build is missing, the readable source is valid JS too, only | |
| 1245 | + * larger: printing nothing would leave every delayed script parked for | |
| 1246 | + * good, because the tags are already rewritten by the time this runs. | |
| 1247 | + */ | |
| 1248 | + private static function delay_bootstrap_js(): string { | |
| 1249 | + if ( null !== self::$delay_bootstrap_js ) { | |
| 1250 | + return self::$delay_bootstrap_js; | |
| 1251 | + } | |
| 1252 | + $root = dirname( __DIR__ ); | |
| 1253 | + $built = $root . '/assets/delay-bootstrap.min.js'; | |
| 1254 | + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- a local plugin file, not a remote URL. | |
| 1255 | + $js = is_readable( $built ) ? (string) file_get_contents( $built ) : ''; | |
| 1256 | + if ( '' !== $js ) { | |
| 1257 | + $js = (string) preg_replace( '#\A/\*[^\n]*\*/\n#', '', $js ); | |
| 1258 | + } else { | |
| 1259 | + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- a local plugin file, not a remote URL. | |
| 1260 | + $js = (string) file_get_contents( $root . '/includes/js/delay-bootstrap.js' ); | |
| 1261 | + } | |
| 1262 | + self::$delay_bootstrap_js = trim( $js ); | |
| 1263 | + return self::$delay_bootstrap_js; | |
| 1264 | + } | |
| 1265 | + | |
| 1266 | + /** | |
| 669 | 1267 | * Filter: `style_loader_tag` — wrap stylesheets in the |
| 670 | 1268 | * print → onload="all" pattern so they download non-blocking. |
| 671 | 1269 | * Pairs with critical CSS workflows. Adds a <noscript> fallback so |
| 672 | 1270 | * users with JS disabled still get styles applied (via media="all"). |
| @@ -686,8 +1284,21 @@ | ||
| 686 | 1284 | // want to fight with explicit author intent. |
| 687 | 1285 | if ( false === stripos( $tag, 'rel=\'stylesheet\'' ) && false === stripos( $tag, 'rel="stylesheet"' ) ) { |
| 688 | 1286 | return $tag; |
| 689 | 1287 | } |
| 1288 | + // No critical CSS for this page: every stylesheet stays blocking. | |
| 1289 | + // | |
| 1290 | + // Deferring a stylesheet only helps when something already styles the | |
| 1291 | + // first screen. Without that, the page paints unstyled and then jumps | |
| 1292 | + // when the sheets arrive. Measured on the Templately Astoria pages | |
| 1293 | + // (Elementor and a block theme): CLS 0.43-1.27 and 15-43 points lower | |
| 1294 | + // on 7 of 8 pages than the same settings without async CSS. The guards | |
| 1295 | + // below narrow the damage; this one removes it. WP Rocket, LiteSpeed, | |
| 1296 | + // Jetpack Boost and FlyingPress likewise never defer CSS without | |
| 1297 | + // critical CSS. (#588) | |
| 1298 | + if ( ! self::page_has_critical_css() ) { | |
| 1299 | + return $tag; | |
| 1300 | + } | |
| 690 | 1301 | // The stylesheets that lay the page out stay render-blocking. |
| 691 | 1302 | // |
| 692 | 1303 | // This transform moves a sheet to AFTER first paint. That is the |
| 693 | 1304 | // point of it — but a sheet the layout depends on is then missing |
| @@ -994,12 +1605,19 @@ | ||
| 994 | 1605 | * than a hard-coded list. |
| 995 | 1606 | * - WordPress' own BLOCK and layout sheets (`wp-block-library`, |
| 996 | 1607 | * `global-styles`, `classic-theme-styles`). These style block |
| 997 | 1608 | * content on the front end and are as structural as the theme's. |
| 1609 | + * - A page builder's GRID sheets: the rows, columns, sections and | |
| 1610 | + * containers everything else sits in (`kadence-blocks-rowlayout`, | |
| 1611 | + * `kadence-blocks-column`, `elementor-frontend`, `elementor-post-N`). | |
| 1612 | + * On a builder page these lay out the hero, not the theme. Deferred, | |
| 1613 | + * the hero painted as one stacked column and then snapped into its | |
| 1614 | + * grid: CLS 0.665 on desktop, from one row. | |
| 998 | 1615 | * |
| 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. | |
| 1616 | + * Everything else — plugin sheets, icon fonts, buttons, forms, the | |
| 1617 | + * builder's per-widget sheets, the long tail that makes async CSS worth | |
| 1618 | + * having — is still deferred, so the optimization keeps most of its | |
| 1619 | + * benefit. | |
| 1002 | 1620 | * |
| 1003 | 1621 | * A site WITH critical CSS can defer these too; that is what the |
| 1004 | 1622 | * `xspeed_async_css_layout_critical` filter is for. |
| 1005 | 1623 | * |
| @@ -1016,19 +1634,21 @@ | ||
| 1016 | 1634 | 'wp-block-library-theme', |
| 1017 | 1635 | 'global-styles', |
| 1018 | 1636 | 'classic-theme-styles', |
| 1019 | 1637 | ); |
| 1020 | - $critical = in_array( $handle, $core, true ); | |
| 1638 | + $critical = in_array( $handle, $core, true ) || self::is_builder_grid_style( $handle ); | |
| 1021 | 1639 | |
| 1022 | 1640 | // The active theme's own sheets. |
| 1023 | 1641 | // |
| 1024 | 1642 | // Matched on the theme stem, but NOT as a bare prefix: a plugin from |
| 1025 | 1643 | // 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. | |
| 1644 | + // `kadence-blocks-image` and `kadence-fonts-gfonts` come from the | |
| 1645 | + // Kadence Blocks PLUGIN and a webfont loader). Treating every such | |
| 1646 | + // sheet as layout-critical would leave almost nothing deferred and | |
| 1647 | + // quietly undo the feature; the builder's grid sheets are caught | |
| 1648 | + // above by what they do, not whose they are. So the stem must be | |
| 1649 | + // followed by a recognised theme-area segment, which is how themes | |
| 1650 | + // name their split sheets. | |
| 1031 | 1651 | if ( ! $critical && function_exists( 'get_template' ) ) { |
| 1032 | 1652 | $areas = array( |
| 1033 | 1653 | 'style', |
| 1034 | 1654 | 'global', |
| @@ -1073,8 +1693,28 @@ | ||
| 1073 | 1693 | return (bool) apply_filters( 'xspeed_async_css_layout_critical', $critical, $handle ); |
| 1074 | 1694 | } |
| 1075 | 1695 | |
| 1076 | 1696 | /** |
| 1697 | + * Whether a handle is a page builder's grid sheet. | |
| 1698 | + * | |
| 1699 | + * Matched on the last segment of the handle, so a builder that names its | |
| 1700 | + * row sheet `acme-blocks-row-layout` is covered without being listed. The | |
| 1701 | + * segments are the ones that only ever carry structure; a button, image | |
| 1702 | + * or form sheet styles an element inside the grid, and the grid holds its | |
| 1703 | + * place while that sheet loads. | |
| 1704 | + * | |
| 1705 | + * @param string $handle Lowercase stylesheet handle. | |
| 1706 | + */ | |
| 1707 | + private static function is_builder_grid_style( string $handle ): bool { | |
| 1708 | + if ( preg_match( '#(?:^|-)(?:rowlayout|row-layout|column|columns|container|section|grid)$#', $handle ) ) { | |
| 1709 | + return true; | |
| 1710 | + } | |
| 1711 | + // Builders whose grid lives in a sheet named after the builder or the | |
| 1712 | + // post, not after a structural element. | |
| 1713 | + return (bool) preg_match( '#^(?:elementor-frontend|elementor-post-\d+|fl-builder-layout(?:-\d+)?|generateblocks)$#', $handle ); | |
| 1714 | + } | |
| 1715 | + | |
| 1716 | + /** | |
| 1077 | 1717 | * Filter: `style_loader_src` + `script_loader_src` — strip the |
| 1078 | 1718 | * ?ver=X.Y query string that WP appends for cache busting. Some |
| 1079 | 1719 | * CDNs / reverse proxies cache better when the URL has no query. |
| 1080 | 1720 | * |
| @@ -1275,12 +1915,231 @@ | ||
| 1275 | 1915 | 'wp-url', |
| 1276 | 1916 | 'wp-api-fetch', |
| 1277 | 1917 | ); |
| 1278 | 1918 | |
| 1279 | - private static function is_excluded_script( string $handle, string $src ): bool { | |
| 1919 | + /** | |
| 1920 | + * Consent managers are never deferred, and never delayed by a broad | |
| 1921 | + * setting — only a delay_js_targets entry that NAMES the vendor lifts | |
| 1922 | + * the floor (see user_named_consent_manager()); the | |
| 1923 | + * `xspeed_js_exclusion_floor` filter remains the code-level override. | |
| 1924 | + * | |
| 1925 | + * A consent banner is drawn by JavaScript, and it is the one thing on | |
| 1926 | + * the page that has to appear before anything else happens. Delay it | |
| 1927 | + * and a visitor who lands, reads and leaves without touching the page | |
| 1928 | + * is never asked — on an opt-in configuration the site then ran | |
| 1929 | + * without ever offering the choice. | |
| 1930 | + * | |
| 1931 | + * The editable list cannot carry this. A stored value replaces the | |
| 1932 | + * schema default outright (Settings_Manager::get()), so widening that | |
| 1933 | + * default would reach fresh installs only, and clearing the textarea | |
| 1934 | + * would drop the protection again. Same floor pattern as | |
| 1935 | + * Server_Rules::COOKIE_FLOOR. Trim or extend it through | |
| 1936 | + * `xspeed_js_exclusion_floor`. | |
| 1937 | + * | |
| 1938 | + * A URL token cannot survive a rewrite of that URL: Minify JS rewrites a | |
| 1939 | + * local script to a hashed /cache/xspeed/min/ path, and Combine JS folds | |
| 1940 | + * it into a bundle. On the enqueue path original_src() gives the pre-minify | |
| 1941 | + * URL back, but the buffer sweep has only the tag -- so with Minify JS on | |
| 1942 | + * and the `id` stripped, a banner shipped un-minified is not recognised. | |
| 1943 | + * Documented in docs/user/minification.md rather than papered over. | |
| 1944 | + * | |
| 1945 | + * Each entry goes through target_matches(): an exact handle OR a | |
| 1946 | + * case-insensitive URL substring. Both passes can match either — the | |
| 1947 | + * enqueue path is handed the handle, and the buffer sweep reads it back | |
| 1948 | + * out of the tag's `id`. A URL token additionally covers a banner that | |
| 1949 | + * was never enqueued at all, which is how Cookiebot prints itself. (#275) | |
| 1950 | + */ | |
| 1951 | + private const CONSENT_MANAGER_FLOOR = array( | |
| 1952 | + // Prefer a plugin-directory or vendor-host URL token over a handle. | |
| 1953 | + // A handle is only readable on the enqueue path and, on the buffer | |
| 1954 | + // sweep, only if the tag still carries the `id` WordPress prints — | |
| 1955 | + // which another plugin can strip. A URL token matches on both passes | |
| 1956 | + // and covers a banner that was never enqueued at all. (#275 QA) | |
| 1957 | + | |
| 1958 | + // CookieYes / GDPR Cookie Consent. Handle and plugin directory are | |
| 1959 | + // the same string, so this covers both paths. | |
| 1960 | + 'cookie-law-info', | |
| 1961 | + // Complianz: the plugin directory, covering -gdpr and -gdpr-premium. | |
| 1962 | + // Was the `cmplz-cookiebanner` handle, which needed the `id` tag. | |
| 1963 | + 'complianz', | |
| 1964 | + // NotificationX runs its GDPR cookie notice off the same handle as | |
| 1965 | + // every other notification, so excluding it excludes them all. That | |
| 1966 | + // is what the plugin's own team asked for. Directory token covers | |
| 1967 | + // the Pro build too; was the `notificationx-public` handle. | |
| 1968 | + 'notificationx', | |
| 1969 | + // Cookiebot prints its loader straight into wp_head, so only the | |
| 1970 | + // buffer sweep ever sees it. This is the token Cookiebot's own WP | |
| 1971 | + // Rocket and LiteSpeed integrations exclude. | |
| 1972 | + 'consent.cookiebot.com', | |
| 1973 | + // Cookie Notice — named in the original report and one of the most | |
| 1974 | + // installed consent plugins. Its banner is enqueued from | |
| 1975 | + // /plugins/cookie-notice/js/front.min.js. | |
| 1976 | + 'cookie-notice', | |
| 1977 | + // Cookie Notice in Cookie Compliance mode prints a different loader, | |
| 1978 | + // whose host is overridable via CN_APP_WIDGET_URL — so key on the | |
| 1979 | + // filename, not the CDN host. | |
| 1980 | + 'hu-banner', | |
| 1981 | + // Moove GDPR Cookie Compliance. Directory token: its handle | |
| 1982 | + // (`moove_gdpr_frontend`) does not appear in its own URL. | |
| 1983 | + 'gdpr-cookie-compliance', | |
| 1984 | + // Termly's resource blocker, which also covers the legacy embed. | |
| 1985 | + 'app.termly.io', | |
| 1986 | + // Usercentrics, reached three ways: Cookiebot's UC mode | |
| 1987 | + // (web.cmp.usercentrics.eu), Termageddon (app.usercentrics.eu) and | |
| 1988 | + // the privacy proxy. | |
| 1989 | + 'usercentrics.eu', | |
| 1990 | + // Iubenda: both the consent solution and the consent database SDK. | |
| 1991 | + 'cdn.iubenda.com', | |
| 1992 | + // OneTrust. Pasted snippet rather than a wordpress.org plugin, so | |
| 1993 | + // this is the SDK host rather than a verified plugin path. | |
| 1994 | + 'cdn.cookielaw.org', | |
| 1995 | + // Borlabs is commercial and renames its files per release; the | |
| 1996 | + // vendor's own guidance is that this string stays in every path. | |
| 1997 | + 'borlabs-cookie', | |
| 1998 | + // Real Cookie Banner, free and pro. Its anti-adblock mode serves the | |
| 1999 | + // banner from an anonymised path that no URL token can match — use | |
| 2000 | + // `xspeed_js_exclusion_floor` to add the handle on such a site. | |
| 2001 | + 'real-cookie-banner', | |
| 2002 | + // SureCookie. | |
| 2003 | + 'surecookie', | |
| 2004 | + ); | |
| 2005 | + | |
| 2006 | + /** | |
| 2007 | + * What a site owner types to name each floor entry, and what the admin | |
| 2008 | + * shows them. Keyed by CONSENT_MANAGER_FLOOR token; a test holds the two | |
| 2009 | + * in step. | |
| 2010 | + * | |
| 2011 | + * The keyword is the part of the token a person would actually write | |
| 2012 | + * (`cookiebot`, not `consent.cookiebot.com`), and it is always a substring | |
| 2013 | + * of the token, so an entry that names the vendor this way still matches | |
| 2014 | + * the vendor's URL. A brand name that appears nowhere in the URL | |
| 2015 | + * (`cookieyes`, `onetrust`, `cmplz`) is deliberately not a keyword: it | |
| 2016 | + * could never match the tag, so offering it would promise a lift that | |
| 2017 | + * cannot happen. The exact handle always works as well. | |
| 2018 | + * | |
| 2019 | + * Cookiebot in Usercentrics CMP mode loads from web.cmp.usercentrics.eu, | |
| 2020 | + * so the floor catches it as Usercentrics and `usercentrics` names it, | |
| 2021 | + * not `cookiebot`. | |
| 2022 | + */ | |
| 2023 | + private const CONSENT_MANAGER_NAMES = array( | |
| 2024 | + 'cookie-law-info' => array( 'label' => 'CookieYes', 'keyword' => 'cookie-law-info' ), | |
| 2025 | + 'complianz' => array( 'label' => 'Complianz', 'keyword' => 'complianz' ), | |
| 2026 | + 'notificationx' => array( 'label' => 'NotificationX', 'keyword' => 'notificationx' ), | |
| 2027 | + 'consent.cookiebot.com' => array( 'label' => 'Cookiebot', 'keyword' => 'cookiebot' ), | |
| 2028 | + 'cookie-notice' => array( 'label' => 'Cookie Notice', 'keyword' => 'cookie-notice' ), | |
| 2029 | + 'hu-banner' => array( 'label' => 'Cookie Notice (Cookie Compliance)', 'keyword' => 'hu-banner' ), | |
| 2030 | + 'gdpr-cookie-compliance' => array( 'label' => 'GDPR Cookie Compliance (Moove)', 'keyword' => 'gdpr-cookie-compliance' ), | |
| 2031 | + 'app.termly.io' => array( 'label' => 'Termly', 'keyword' => 'termly' ), | |
| 2032 | + 'usercentrics.eu' => array( 'label' => 'Usercentrics', 'keyword' => 'usercentrics' ), | |
| 2033 | + 'cdn.iubenda.com' => array( 'label' => 'Iubenda', 'keyword' => 'iubenda' ), | |
| 2034 | + 'cdn.cookielaw.org' => array( 'label' => 'OneTrust', 'keyword' => 'cookielaw' ), | |
| 2035 | + 'borlabs-cookie' => array( 'label' => 'Borlabs Cookie', 'keyword' => 'borlabs' ), | |
| 2036 | + 'real-cookie-banner' => array( 'label' => 'Real Cookie Banner', 'keyword' => 'real-cookie-banner' ), | |
| 2037 | + 'surecookie' => array( 'label' => 'SureCookie', 'keyword' => 'surecookie' ), | |
| 2038 | + ); | |
| 2039 | + | |
| 2040 | + /** | |
| 2041 | + * "Label (keyword)" for every built-in consent manager, for the admin. | |
| 2042 | + * | |
| 2043 | + * Reads the built-in list, not the filtered floor: the admin describes | |
| 2044 | + * what ships, and a site that trimmed the floor in code knows it did. | |
| 2045 | + * | |
| 2046 | + * @return string[] | |
| 2047 | + */ | |
| 2048 | + public static function consent_manager_labels(): array { | |
| 2049 | + $out = array(); | |
| 2050 | + foreach ( self::CONSENT_MANAGER_FLOOR as $token ) { | |
| 2051 | + $name = self::CONSENT_MANAGER_NAMES[ $token ] ?? array( | |
| 2052 | + 'label' => $token, | |
| 2053 | + 'keyword' => $token, | |
| 2054 | + ); | |
| 2055 | + $out[] = $name['label'] . ' (' . $name['keyword'] . ')'; | |
| 2056 | + } | |
| 2057 | + return $out; | |
| 2058 | + } | |
| 2059 | + | |
| 2060 | + /** | |
| 2061 | + * Per-request memo for exclusion_floor(). Null = not resolved. | |
| 2062 | + * | |
| 2063 | + * @var string[]|null | |
| 2064 | + */ | |
| 2065 | + private static $exclusion_floor = null; | |
| 2066 | + | |
| 2067 | + /** | |
| 2068 | + * The built-in exclusion floor, after the site has had its say. | |
| 2069 | + * | |
| 2070 | + * @return string[] | |
| 2071 | + */ | |
| 2072 | + private static function exclusion_floor(): array { | |
| 2073 | + if ( null === self::$exclusion_floor ) { | |
| 2074 | + /** | |
| 2075 | + * Scripts that are never deferred or delayed, whatever the | |
| 2076 | + * user's exclusion list holds. Each entry is an exact script | |
| 2077 | + * handle or a case-insensitive URL substring. | |
| 2078 | + * | |
| 2079 | + * Return the array minus a token to let Delay JS postpone that | |
| 2080 | + * consent manager on purpose; add one to protect another script. | |
| 2081 | + * | |
| 2082 | + * @param string[] $floor Built-in floor. | |
| 2083 | + */ | |
| 2084 | + $floor = apply_filters( 'xspeed_js_exclusion_floor', self::CONSENT_MANAGER_FLOOR ); | |
| 2085 | + self::$exclusion_floor = array_values( | |
| 2086 | + array_filter( array_map( 'strval', (array) $floor ), static fn( $t ) => '' !== $t ) | |
| 2087 | + ); | |
| 2088 | + } | |
| 2089 | + return self::$exclusion_floor; | |
| 2090 | + } | |
| 2091 | + | |
| 2092 | + /** | |
| 2093 | + * @param string $handle Script handle ('' on the buffer sweep | |
| 2094 | + * when no id survived). | |
| 2095 | + * @param string $src Script URL. | |
| 2096 | + * @param bool $named_lifts_floor Delay paths only: a delay_js_targets | |
| 2097 | + * entry that NAMES the consent manager | |
| 2098 | + * passes the floor (see | |
| 2099 | + * user_named_consent_manager()). Typing a | |
| 2100 | + * consent manager's name into an | |
| 2101 | + * allow-list is the site owner taking the | |
| 2102 | + * consent-timing decision back — GDPR is | |
| 2103 | + * theirs to weigh, not ours; the floor | |
| 2104 | + * only exists so Delay JS can't hide a | |
| 2105 | + * banner NOBODY pointed at. Their own | |
| 2106 | + * exclusion list, ALWAYS_EXCLUDED_HANDLES | |
| 2107 | + * and our beacons still win: on a | |
| 2108 | + * conflict between the user's two lists, | |
| 2109 | + * protection beats postponement. | |
| 2110 | + */ | |
| 2111 | + private static function is_excluded_script( string $handle, string $src, bool $named_lifts_floor = false ): bool { | |
| 1280 | 2112 | if ( in_array( $handle, self::ALWAYS_EXCLUDED_HANDLES, true ) ) { |
| 1281 | 2113 | return true; |
| 1282 | 2114 | } |
| 2115 | + // Never defer or delay our own scripts. The fold and RUM beacons | |
| 2116 | + // measure the FIRST paint — delayed to first interaction they | |
| 2117 | + // measure a scrolled page or nothing, so fold quorum never fills | |
| 2118 | + // and full CSS deferral never licenses. Found live: delay_js with | |
| 2119 | + // empty targets delayed the fold beacon itself, and the site sat | |
| 2120 | + // at zero fold reports for hours while its stylesheets stayed | |
| 2121 | + // render-blocking. Prefix, not a handle list, so a Pro module's | |
| 2122 | + // beacon added later cannot re-open the hole. | |
| 2123 | + if ( 0 === strpos( $handle, 'xspeed-' ) ) { | |
| 2124 | + return true; | |
| 2125 | + } | |
| 2126 | + // Ahead of the user list, and ahead of the empty-list early return | |
| 2127 | + // below: an install that saved the Minify panel before this shipped | |
| 2128 | + // has a stored list that knows nothing about consent managers, and | |
| 2129 | + // one that cleared the textarea has no list at all. Neither may | |
| 2130 | + // hide the banner. (#275) | |
| 2131 | + foreach ( self::exclusion_floor() as $needle ) { | |
| 2132 | + if ( self::target_matches( $needle, $handle, $src ) ) { | |
| 2133 | + // `continue`, not `break`: a second floor token matching the | |
| 2134 | + // same tag has to be named too, or a filter-added token | |
| 2135 | + // would be lifted by an entry that names only the first. | |
| 2136 | + if ( $named_lifts_floor && self::user_named_consent_manager( $needle, $handle, $src ) ) { | |
| 2137 | + continue; | |
| 2138 | + } | |
| 2139 | + return true; | |
| 2140 | + } | |
| 2141 | + } | |
| 1283 | 2142 | $opts = self::opts(); |
| 1284 | 2143 | $excluded = is_array( $opts['defer_js_excluded'] ?? null ) ? $opts['defer_js_excluded'] : array(); |
| 1285 | 2144 | if ( empty( $excluded ) ) { |
| 1286 | 2145 | return false; |
| @@ -1347,8 +2206,131 @@ | ||
| 1347 | 2206 | } |
| 1348 | 2207 | return false; |
| 1349 | 2208 | } |
| 1350 | 2209 | |
| 2210 | + /** | |
| 2211 | + * Whether a delay_js_targets entry NAMES the consent manager whose floor | |
| 2212 | + * token matched this tag, and so lifts the floor for it. | |
| 2213 | + * | |
| 2214 | + * is_user_named_target() is not enough here: it asks whether any entry | |
| 2215 | + * matches the tag, and a delay target is a URL substring. `/plugins/`, | |
| 2216 | + * `.js`, `min.js`, `frontend` or the site's own host each match every | |
| 2217 | + * consent banner on the page, so one broad entry switched the floor off | |
| 2218 | + * for all of them and brought #275 back. An entry names the vendor when | |
| 2219 | + * it is the exact handle, or when it contains the vendor's keyword (or | |
| 2220 | + * its floor token) and still matches the tag, so `notificationx` and | |
| 2221 | + * `/plugins/notificationx/` lift NotificationX, `termly` cannot lift | |
| 2222 | + * Cookiebot, and `/plugins/` lifts nothing. | |
| 2223 | + * | |
| 2224 | + * A token added through `xspeed_js_exclusion_floor` has no keyword, so | |
| 2225 | + * only an entry containing that token, or the exact handle, names it. | |
| 2226 | + * | |
| 2227 | + * @param string $floor_token The floor entry that matched this tag. | |
| 2228 | + * @param string $handle Script handle ('' when unknown). | |
| 2229 | + * @param string $src Script URL, or the body on the inline pass. | |
| 2230 | + */ | |
| 2231 | + private static function user_named_consent_manager( string $floor_token, string $handle, string $src ): bool { | |
| 2232 | + $opts = self::opts(); | |
| 2233 | + $targets = is_array( $opts['delay_js_targets'] ?? null ) ? $opts['delay_js_targets'] : array(); | |
| 2234 | + $names = array( $floor_token ); | |
| 2235 | + if ( isset( self::CONSENT_MANAGER_NAMES[ $floor_token ] ) ) { | |
| 2236 | + $names[] = self::CONSENT_MANAGER_NAMES[ $floor_token ]['keyword']; | |
| 2237 | + } | |
| 2238 | + foreach ( $targets as $needle ) { | |
| 2239 | + $needle = trim( (string) $needle ); | |
| 2240 | + if ( '' === $needle ) { | |
| 2241 | + continue; | |
| 2242 | + } | |
| 2243 | + $names_it = '' !== $handle && $handle === $needle; | |
| 2244 | + foreach ( $names as $name ) { | |
| 2245 | + if ( false !== stripos( $needle, $name ) ) { | |
| 2246 | + $names_it = true; | |
| 2247 | + break; | |
| 2248 | + } | |
| 2249 | + } | |
| 2250 | + if ( $names_it && self::target_matches( $needle, $handle, $src ) ) { | |
| 2251 | + return true; | |
| 2252 | + } | |
| 2253 | + } | |
| 2254 | + return false; | |
| 2255 | + } | |
| 2256 | + | |
| 2257 | + /** Both toggles on: delay_js and its carry-the-inline-snippets mode. */ | |
| 2258 | + private static function smart_delay_enabled(): bool { | |
| 2259 | + $opts = self::opts(); | |
| 2260 | + return ! empty( $opts['delay_js'] ) && ! empty( $opts['delay_js_smart'] ); | |
| 2261 | + } | |
| 2262 | + | |
| 2263 | + /** | |
| 2264 | + * Would Smart Delay postpone this handle's tag? | |
| 2265 | + * | |
| 2266 | + * The snippet-parking filter runs when WordPress prints a handle's | |
| 2267 | + * `before` snippet — BEFORE script_loader_tag sees the tag itself — so | |
| 2268 | + * the decision cannot be read back from what happened to the tag; both | |
| 2269 | + * sides evaluate this same predicate. It mirrors the handle/src checks | |
| 2270 | + * of delay_script_tag() only: the tag-level outs there (an optimizer | |
| 2271 | + * opt-out attribute, a non-executable type) are invisible here, so a | |
| 2272 | + * tag that keeps itself eager through one of those can still have its | |
| 2273 | + * snippets parked. That parks an init until first interaction rather | |
| 2274 | + * than throwing, and Smart Delay is opt-in — acceptable, and documented | |
| 2275 | + * on the setting. | |
| 2276 | + */ | |
| 2277 | + private static function smart_delays_handle( string $handle ): bool { | |
| 2278 | + if ( '' === $handle ) { | |
| 2279 | + return false; | |
| 2280 | + } | |
| 2281 | + $src = self::original_src( $handle ); | |
| 2282 | + if ( self::is_excluded_script( $handle, $src, true ) ) { | |
| 2283 | + return false; | |
| 2284 | + } | |
| 2285 | + return self::is_delay_target( $handle, $src ); | |
| 2286 | + } | |
| 2287 | + | |
| 2288 | + /** | |
| 2289 | + * Park a delayed handle's own before/after snippet, in Smart Delay mode. | |
| 2290 | + * | |
| 2291 | + * Runs on `wp_inline_script_attributes`, which fires for every inline | |
| 2292 | + * script WordPress prints itself — so it works on pages the HTML buffer | |
| 2293 | + * never filters (a BYPASS route like /cart), where the handle's tag is | |
| 2294 | + * still delayed by script_loader_tag. `-js-extra` stays eager on | |
| 2295 | + * purpose: it is data assignments, harmless early and sometimes read by | |
| 2296 | + * eager code. | |
| 2297 | + * | |
| 2298 | + * @param mixed $attributes Inline script attributes. | |
| 2299 | + * @param string $javascript The snippet body. | |
| 2300 | + * @return mixed | |
| 2301 | + */ | |
| 2302 | + public static function park_smart_inline( $attributes, $javascript = '' ) { | |
| 2303 | + if ( ! is_array( $attributes ) || ! self::smart_delay_enabled() || self::skip_in_non_frontend_context() ) { | |
| 2304 | + return $attributes; | |
| 2305 | + } | |
| 2306 | + $id = isset( $attributes['id'] ) ? (string) $attributes['id'] : ''; | |
| 2307 | + if ( ! preg_match( '#^(.+)-js-(?:before|after)$#', $id, $m ) ) { | |
| 2308 | + return $attributes; | |
| 2309 | + } | |
| 2310 | + if ( ! self::smart_delays_handle( $m[1] ) ) { | |
| 2311 | + return $attributes; | |
| 2312 | + } | |
| 2313 | + $type = isset( $attributes['type'] ) ? (string) $attributes['type'] : ''; | |
| 2314 | + if ( in_array( $type, self::NON_EXECUTABLE_TYPES, true ) ) { | |
| 2315 | + return $attributes; // data, or parked by someone else on purpose. | |
| 2316 | + } | |
| 2317 | + // A delayed document.write replays after the document has closed | |
| 2318 | + // and replaces the page. Same rule as delay_inline_snippets(). | |
| 2319 | + if ( false !== stripos( (string) $javascript, 'document.write' ) ) { | |
| 2320 | + return $attributes; | |
| 2321 | + } | |
| 2322 | + if ( '' !== $type && ! in_array( $type, self::DEFAULT_JS_TYPES, true ) ) { | |
| 2323 | + $stash = (string) preg_replace( '#[^a-z0-9/+.\-]#', '', $type ); | |
| 2324 | + if ( '' !== $stash ) { | |
| 2325 | + $attributes['data-xs-type'] = $stash; | |
| 2326 | + } | |
| 2327 | + } | |
| 2328 | + $attributes['type'] = 'text/xspeed-delayed'; | |
| 2329 | + $attributes['data-xs-delay'] = '1'; | |
| 2330 | + return $attributes; | |
| 2331 | + } | |
| 2332 | + | |
| 1351 | 2333 | private static function is_delay_target( string $handle, string $src ): bool { |
| 1352 | 2334 | $opts = self::opts(); |
| 1353 | 2335 | $targets = is_array( $opts['delay_js_targets'] ?? null ) ? $opts['delay_js_targets'] : array(); |
| 1354 | 2336 | $targets = array_filter( array_map( 'strval', $targets ), static fn( $t ) => '' !== $t ); |
| @@ -1485,9 +2467,13 @@ | ||
| 1485 | 2467 | self::$opts = null; |
| 1486 | 2468 | self::$uploads_base = null; |
| 1487 | 2469 | self::$delay_bootstrap_printed = false; |
| 1488 | 2470 | self::$js_measured_layout = null; |
| 2471 | + self::$has_critical_css = null; | |
| 2472 | + self::$exclusion_floor = null; | |
| 1489 | 2473 | self::$inline_bound_handles = null; |
| 2474 | + self::$pristine_tag = array(); | |
| 2475 | + self::$our_late_attrs = array(); | |
| 1490 | 2476 | } |
| 1491 | 2477 | |
| 1492 | 2478 | /** |
| 1493 | 2479 | * Per-request memo for inline_bound_handles(). Null = not resolved. |
| @@ -1639,8 +2625,41 @@ | ||
| 1639 | 2625 | * |
| 1640 | 2626 | * @var bool|null |
| 1641 | 2627 | */ |
| 1642 | 2628 | private static $js_measured_layout = null; |
| 2629 | + | |
| 2630 | + /** | |
| 2631 | + * Per-request memo for page_has_critical_css(). Null = not resolved. | |
| 2632 | + * | |
| 2633 | + * @var bool|null | |
| 2634 | + */ | |
| 2635 | + private static $has_critical_css = null; | |
| 2636 | + | |
| 2637 | + /** | |
| 2638 | + * Does something inline critical CSS for the page being served? | |
| 2639 | + * | |
| 2640 | + * Free generates none, so the answer comes from the filter: an extension | |
| 2641 | + * that inlines critical CSS for this page returns true, and a site whose | |
| 2642 | + * theme ships its own can too. Resolved once per request, because every | |
| 2643 | + * stylesheet tag asks. | |
| 2644 | + */ | |
| 2645 | + public static function page_has_critical_css(): bool { | |
| 2646 | + if ( null === self::$has_critical_css ) { | |
| 2647 | + /** | |
| 2648 | + * Whether the page being served has critical CSS inlined in its head. | |
| 2649 | + * | |
| 2650 | + * Async CSS defers stylesheets only when this is true; without | |
| 2651 | + * critical CSS it leaves them render-blocking, because deferring | |
| 2652 | + * them makes the page paint unstyled and shift. Return true when | |
| 2653 | + * something inlines critical CSS for this page, or to keep deferring | |
| 2654 | + * without it. | |
| 2655 | + * | |
| 2656 | + * @param bool $has_critical_css Default false. | |
| 2657 | + */ | |
| 2658 | + self::$has_critical_css = (bool) apply_filters( 'xspeed_async_css_page_has_critical_css', false ); | |
| 2659 | + } | |
| 2660 | + return self::$has_critical_css; | |
| 2661 | + } | |
| 1643 | 2662 | |
| 1644 | 2663 | /** |
| 1645 | 2664 | * Scripts that lay out the page by measuring the DOM. |
| 1646 | 2665 | * |