PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.4.2
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.4.2
1.4.2 1.4.1 1.4.0 1.3.7 1.3.6 1.3.5 1.3.4 1.3.3 1.3.2 1.3.1 1.3.0 1.2.4 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 All 36 releases
← All changes | includes/class-minify-filters.php +1088 -117 1.3.4 → 1.4.2 View file →
@@ -185,9 +185,9 @@
185 185 // so carry it — and everything else the late filter set in the
186 186 // same pass — over. A consumer reading the rendered HTML (or
187 187 // our own buffer passes) must still see the opt-out it asked
188 188 // for.
189 - $tag = self::copy_late_attributes( $tag, $pristine );
189 + $tag = self::copy_late_attributes( $tag, $pristine, $handle );
190 190 }
191 191 // The snapshot was taken on `script_loader_tag`, by which point
192 192 // `script_loader_src` (priority 10) had ALREADY swapped in the
193 193 // hashed cache URL — so reverting the tag alone still leaves the
@@ -230,9 +230,9 @@
230 230 *
231 231 * @param string $from Tag as the late filter left it.
232 232 * @param string $to Snapshot tag to stamp onto.
233 233 */
234 - private static function copy_late_attributes( string $from, string $to ): string {
234 + private static function copy_late_attributes( string $from, string $to, string $handle ): string {
235 235 $late_tags = self::open_tags( $from );
236 236 $to_tags = self::open_tags( $to );
237 237 if ( empty( $late_tags ) || empty( $to_tags ) || count( $late_tags ) !== count( $to_tags ) ) {
238 238 // Counts differ when a stamper/blocker injected or replaced a
@@ -254,9 +254,9 @@
254 254 // later. (#469)
255 255 $out = $to;
256 256 // Right to left: an earlier splice would shift every later offset.
257 257 for ( $i = count( $to_tags ) - 1; $i >= 0; $i-- ) {
258 - $add = self::late_attribute_delta( $late_tags[ $i ]['attrs'], $to_tags[ $i ]['attrs'] );
258 + $add = self::late_attribute_delta( $late_tags[ $i ]['attrs'], $to_tags[ $i ]['attrs'], $handle );
259 259 if ( '' !== $add ) {
260 260 $out = substr_replace( $out, $add, $to_tags[ $i ]['attrs_end'], 0 );
261 261 }
262 262 }
@@ -305,14 +305,25 @@
305 305 }
306 306
307 307 /**
308 308 * The attributes present on the late tag but not the snapshot, minus
309 - * the ones our own transforms add.
309 + * the ones OUR transforms put there for this handle.
310 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 + *
311 321 * @param string $late_attrs Attribute string from the transformed tag.
312 322 * @param string $to_attrs Attribute string from the snapshot tag.
323 + * @param string $handle Script handle the tags belong to.
313 324 */
314 - private static function late_attribute_delta( string $late_attrs, string $to_attrs ): string {
325 + private static function late_attribute_delta( string $late_attrs, string $to_attrs, string $handle ): string {
315 326 $pattern = '#\s([-\w:]+)(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s>]*))?#';
316 327 if ( ! preg_match_all( $pattern, $late_attrs, $late, PREG_SET_ORDER ) ) {
317 328 return '';
318 329 }
@@ -324,9 +335,9 @@
324 335 }
325 336 $add = '';
326 337 foreach ( $late as $attr ) {
327 338 $name = strtolower( $attr[1] );
328 - if ( isset( $have[ $name ] ) || in_array( $name, self::OUR_TRANSFORM_ATTRS, true ) ) {
339 + if ( isset( $have[ $name ] ) || 'src' === $name || isset( self::$our_late_attrs[ $handle ][ $name ] ) ) {
329 340 continue;
330 341 }
331 342 if ( 0 === strpos( $name, 'data-xs-' ) ) {
332 343 continue;
@@ -336,21 +347,20 @@
336 347 return $add;
337 348 }
338 349
339 350 /**
340 - * Attributes our own transforms add. Copying any of these from the
341 - * transformed tag back onto the snapshot would re-apply the very
342 - * transform we are undoing:
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)
343 359 *
344 - * defer/async — defer_script_tag()
345 - * type — delay_script_tag() parks an inline block as
346 - * text/xspeed-delayed; a type the author set is on the
347 - * snapshot already and matches by name before we get here
348 - * src — belongs to the snapshot, never to the late tag
349 - *
350 - * `data-xs-*` is handled by prefix separately. (#469)
360 + * @var array<string,array<string,true>>
351 361 */
352 - private const OUR_TRANSFORM_ATTRS = array( 'defer', 'async', 'type', 'src' );
362 + private static $our_late_attrs = array();
353 363
354 364 /**
355 365 * Locate the opening `<script>` that carries the src, falling back to
356 366 * the last one when none does.
@@ -509,8 +519,12 @@
509 519 // bundle's <script> tag intact so the dashboard mounts.
510 520 if ( self::skip_in_non_frontend_context() ) {
511 521 return $tag;
512 522 }
523 + // The author asked every optimizer to leave this tag alone.
524 + if ( self::carries_optimizer_opt_out( $tag ) ) {
525 + return $tag;
526 + }
513 527 if ( '' === (string) $src ) {
514 528 return $tag;
515 529 }
516 530 if ( self::is_excluded_script( (string) $handle, (string) $src ) ) {
@@ -544,9 +558,15 @@
544 558 // dependent that touches a global its dependency defines. (#234)
545 559 //
546 560 // The lookahead scans only within the tag (`[^>]*`) for ` src=`, so
547 561 // an inline `<script id="…-js-before">` can never match.
548 - 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;
549 569 }
550 570
551 571 /**
552 572 * Filter: `script_loader_tag` — rewrite src= to data-xs-src= so the
@@ -565,11 +585,15 @@
565 585 }
566 586 if ( self::skip_in_non_frontend_context() ) {
567 587 return $tag;
568 588 }
569 - 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 ) ) {
570 591 return $tag;
571 592 }
593 + if ( self::is_excluded_script( (string) $handle, (string) $src, true ) ) {
594 + return $tag;
595 + }
572 596 // The tag itself asked to be left alone. (#456)
573 597 if ( self::tag_opts_out( $tag ) ) {
574 598 return $tag;
575 599 }
@@ -584,9 +608,16 @@
584 608 // the moment jquery-core is delayed. A handle the user NAMED in
585 609 // delay_js_targets is still delayed — an explicit entry is the user
586 610 // saying they know the inline consumer is safe to break or absent.
587 611 if ( isset( self::inline_bound_handles()[ (string) $handle ] )
588 - && ! 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() ) {
589 620 return $tag;
590 621 }
591 622 // A non-executable type means this tag is data, or is being held by
592 623 // somebody else on purpose. The buffer pass has always checked this;
@@ -591,9 +622,17 @@
591 622 // A non-executable type means this tag is data, or is being held by
592 623 // somebody else on purpose. The buffer pass has always checked this;
593 624 // the enqueue path did not, so a consent-blocked or JSON-carrying
594 625 // handle could still be rewritten here. (#274)
595 - if ( in_array( self::extract_type( $tag ), self::NON_EXECUTABLE_TYPES, true ) ) {
626 + //
627 + // Read the type from the tag that carries the src. $tag is before +
628 + // external + after, and Smart Delay parks the before/after snippets
629 + // as text/xspeed-delayed before this filter runs. Reading the first
630 + // `type=` in the whole string found the parked snippet, so every
631 + // handle with its own snippets kept a live src behind parked
632 + // snippets.
633 + $type_open = '' !== (string) $src ? self::open_tag_offsets( $tag ) : null;
634 + if ( in_array( self::extract_type( null !== $type_open ? $type_open['attrs'] : $tag ), self::NON_EXECUTABLE_TYPES, true ) ) {
596 635 return $tag;
597 636 }
598 637 // src= variant: swap src → data-xs-src and add data-xs-delay marker.
599 638 if ( '' !== (string) $src ) {
@@ -629,9 +668,9 @@
629 668 // would win over a marker appended behind it and keep executing.
630 669 // A non-default original type is stashed in data-xs-type so the
631 670 // bootstrap can restore it on replay (#274 — type is what a script
632 671 // IS; a parked `type="module"` must come back as a module).
633 - $tag = (string) preg_replace_callback(
672 + $parked = (string) preg_replace_callback(
634 673 '#<script\b([^>]*)>#i',
635 674 static function ( array $m ): string {
636 675 return '<script' . self::park_type_attrs( $m[1] ) . '>';
637 676 },
@@ -637,9 +676,14 @@
637 676 },
638 677 $tag,
639 678 1
640 679 );
641 - return $tag;
680 + if ( $parked !== $tag ) {
681 + // The parked type is ours to drop on a late opt-out revert; an
682 + // author-set type sits on the snapshot and survives regardless.
683 + self::$our_late_attrs[ (string) $handle ]['type'] = true;
684 + }
685 + return $parked;
642 686 }
643 687
644 688 /**
645 689 * Script types the buffer pass must never touch. `<script>` carries
@@ -647,8 +691,104 @@
647 691 * consumers, importmaps must resolve before any module runs, and our
648 692 * own delayed-inline marker is already handled by the bootstrap.
649 693 * Rewriting any of these breaks the page or its metadata.
650 694 */
695 + /**
696 + * Attributes by which a script's own author tells optimizers to stand down.
697 + *
698 + * The report behind #275 also asked us to leave a script alone when its
699 + * author "already marked it to load late". Read literally that means
700 + * `defer`/`async`, and that reading is wrong twice over: `defer` is
701 + * stamped onto every enqueued script by our OWN Defer JS filter at
702 + * priority 20, before Delay JS sees it at 30 — so honouring it would
703 + * switch Delay JS off entirely on sites running both — and `async` is the
704 + * shape of gtag, GTM and every pixel loader, which is precisely the
705 + * payload Delay JS exists to postpone. `defer`/`async` say WHEN TO FETCH,
706 + * not "leave me alone".
707 + *
708 + * These attributes do say it. Each is an established opt-out honoured by
709 + * another optimizer — WP Rocket, LiteSpeed, Autoptimize, NitroPack,
710 + * Jetpack Boost — so an author who prints one has already declared that
711 + * no optimizer should touch this tag. Consent banners are the main
712 + * beneficiary, but the rule is general and needs neither a handle nor a
713 + * recognised URL, so it works identically on both passes.
714 + *
715 + * Two deliberate omissions:
716 + *
717 + * - `data-cfasync="false"` is a Cloudflare Rocket Loader opt-out, and
718 + * ad stacks (Mediavine, Ezoic, AdThrive) print it on exactly the
719 + * heavy loaders a site turns Delay JS on for. Honouring it would
720 + * un-delay the ads.
721 + * - `data-no-minify` is about minification, not execution timing.
722 + */
723 + private const OPT_OUT_ATTRIBUTES = array(
724 + 'nowprocket', // WP Rocket
725 + 'data-nowprocket', // WP Rocket
726 + 'data-no-optimize', // LiteSpeed
727 + 'data-noptimize', // Autoptimize
728 + 'data-no-defer', // used by several optimizers
729 + 'nitro-exclude', // NitroPack
730 + 'data-jetpack-boost', // Jetpack Boost (value "ignore")
731 + 'data-wpmeteor-nooptimize', // WP Meteor
732 + 'data-xs-nodelay', // ours
733 + );
734 +
735 + /**
736 + * Does this tag carry an explicit "optimizers keep out" attribute?
737 + *
738 + * Same `(?<![-\w])` lookbehind the rest of this file uses, so
739 + * `data-nowprocket` does not also satisfy a bare `nowprocket` lookup, and
740 + * a trailing `\b` so `data-no-defer` does not match `data-no-deferral`.
741 + * Bare and valued forms both count: an author writes `nowprocket`,
742 + * `nowprocket=""` and `data-noptimize="1"` interchangeably.
743 + *
744 + * @param string $tag Full opening tag.
745 + */
746 + private static function carries_optimizer_opt_out( string $tag ): bool {
747 + // Read ATTRIBUTE NAMES, not the tag as a string. A substring scan
748 + // matched `src="https://cdn/nowprocket/loader.js"`, `?nowprocket=1`,
749 + // `class="nowprocket"` and any inline body that merely mentioned one
750 + // of these names -- each silently un-delaying a script that should
751 + // have been delayed.
752 + //
753 + // EVERY opening tag is checked, not just the first. On the enqueue
754 + // path WP_Scripts::do_item() hands us translations + before-inline +
755 + // the real tag + after-inline concatenated, so the first `<script`
756 + // is often an inline block and the author's opt-out sits on the
757 + // external tag behind it. Reading only the first tag missed it and
758 + // delayed the script anyway -- the wrong direction: a consent banner
759 + // its author told optimizers to leave alone would not appear.
760 + //
761 + // The tag regex is quote-aware because `[^>]*>` stops at a `>` inside
762 + // a quoted value, and consent managers routinely ship JSON in a
763 + // data-* attribute.
764 + if ( ! preg_match_all( '#<script\b(?:[^>"\']|"[^"]*"|\'[^\']*\')*>#is', $tag, $tags ) ) {
765 + return false;
766 + }
767 +
768 + foreach ( $tags[0] as $open ) {
769 + // Walk name/value pairs. The name pattern is deliberately
770 + // permissive: a name we cannot recognise (Alpine's `@load`, say)
771 + // must still consume ITS OWN VALUE, or the value gets scanned as
772 + // if it were more attribute names.
773 + if ( ! preg_match_all(
774 + '#\s+([^\s=/>]+)(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s>]*))?#s',
775 + substr( $open, 7, -1 ),
776 + $found
777 + ) ) {
778 + continue;
779 + }
780 +
781 + foreach ( $found[1] as $name ) {
782 + if ( in_array( strtolower( $name ), self::OPT_OUT_ATTRIBUTES, true ) ) {
783 + return true;
784 + }
785 + }
786 + }
787 +
788 + return false;
789 + }
790 +
651 791 private const NON_EXECUTABLE_TYPES = array(
652 792 'application/ld+json',
653 793 'application/json',
654 794 'importmap',
@@ -782,10 +922,21 @@
782 922 if ( false !== stripos( $tag, 'data-xs-delay' ) || false !== stripos( $tag, 'data-xs-src' ) ) {
783 923 return $tag;
784 924 }
785 925
786 - // The tag itself asked to be left alone. (#456)
787 - if ( self::tag_opts_out( $tag ) ) {
926 + // The author asked every optimizer to leave this tag alone.
927 + // Checked before src/type: it needs neither, so an
928 + // un-enqueued banner printed straight into wp_head is
929 + // covered the same as an enqueued one.
930 + //
931 + // Both checks, because they disagree on purpose and either
932 + // saying "leave it" is the safe answer. tag_opts_out() is
933 + // dev's (#456) and also drives the late re-check at #469;
934 + // carries_optimizer_opt_out() reads attribute NAMES across
935 + // every opening tag, so it is not fooled by a marker sitting
936 + // inside a quoted value or an inline body, and it knows the
937 + // other optimizers' markers.
938 + if ( self::tag_opts_out( $tag ) || self::carries_optimizer_opt_out( $tag ) ) {
788 939 return $tag;
789 940 }
790 941
791 942 // No src → inline code. The enqueue path owns those; a
@@ -811,37 +962,48 @@
811 962 return $tag;
812 963 }
813 964 }
814 965
815 - // Recover the handle from the tag's id before deciding.
966 + // An ENQUEUED script reaches this sweep too: the enqueue-path
967 + // filter leaves an EXCLUDED tag unmarked, and unmarked is all
968 + // this pass can see. Judging it on its URL alone re-delays the
969 + // very script the exclusion protected — and a handle is not
970 + // generally in its own URL, which is the shape Complianz
971 + // (`cmplz-cookiebanner`), NotificationX (`notificationx-public`)
972 + // and jQuery (`jquery-core`) all have. A site with jquery-core
973 + // excluded still shipped jQuery delayed, and every inline
974 + // `jQuery(...)` on the page threw "jQuery is not defined".
975 + // WordPress prints `id="<handle>-js"` on every enqueued
976 + // script, so the handle is right there in the tag. (#275)
816 977 //
817 - // This pass used to pass '' as the handle, on the reasoning
818 - // that a tag reaching the buffer was never enqueued and so has
819 - // none. That holds for the third-party snippets this pass
820 - // exists for — but NOT for enqueued scripts, which also travel
821 - // through here, and which WordPress prints with
822 - // `id="<handle>-js"`. Passing '' meant every handle-based
823 - // exclusion was silently inert at this layer: the user writes
824 - // `jquery-core`, the enqueue path honours it, and then the
825 - // buffer pass — which only ever compared URLs — delayed the
826 - // very script the list was protecting.
978 + // The lookbehind matters: `data-id="cmplz-cookiebanner-js"` is
979 + // somebody's own attribute, not the handle, and reading it as
980 + // one would shield a script nobody excluded.
827 981 //
828 - // That is how a site with jquery-core AND jquery-migrate
829 - // excluded still shipped jQuery delayed while migrate loaded
830 - // normally, and every inline `jQuery(...)` on the page threw
831 - // "jQuery is not defined". The two behaved differently for no
832 - // reason a user could see, which is what made it look like a
833 - // matching quirk rather than a whole layer ignoring the list.
982 + // Merge note for #374: if a URL->handle map built from
983 + // wp_scripts() lands first, resolve through that and keep
984 + // this as the FALLBACK rather than replacing it. The map is
985 + // keyed on the REGISTERED src, and Minifier::rewrite_script()
986 + // rewrites a local script's URL to a hashed /cache/xspeed/min/
987 + // path at output time -- which is why remember_original_src()
988 + // exists. So with minify_js on, the map misses every minified
989 + // script and an excluded one would be re-delayed here. The
990 + // `id` survives that rewrite.
834 991 $tag_handle = '';
835 - if ( preg_match( '#\sid\s*=\s*(["\'])(.*?)\1#i', $tag, $id_m ) ) {
992 + if ( preg_match( '#(?<![-\w])id\s*=\s*(["\'])(.*?)\1#is', $tag, $id_m ) ) {
836 993 // WP appends `-js`; anything else is somebody's own id and
837 994 // is still worth matching literally.
838 - $tag_handle = (string) preg_replace( '/-js$/', '', $id_m[2] );
995 + $tag_handle = (string) preg_replace( '/-js$/', '', trim( $id_m[2] ) );
839 996 }
840 997
841 - if ( self::is_excluded_script( $tag_handle, $src ) ) {
998 + if ( self::is_excluded_script( $tag_handle, $src, true ) ) {
842 999 return $tag;
843 1000 }
1001 + // The handle is passed to the target test as well, so naming a
1002 + // handle in the delay list behaves the same here as it does on
1003 + // the enqueue path. The two layers disagreeing on what a target
1004 + // means is what made this look like a matching quirk rather
1005 + // than a whole layer ignoring the list.
844 1006 if ( ! self::is_delay_target( $tag_handle, $src ) ) {
845 1007 return $tag;
846 1008 }
847 1009 // Mirror of the enqueue-path guard: a handle that inline code
@@ -903,11 +1065,13 @@
903 1065 if ( empty( $opts['delay_js'] ) ) {
904 1066 return $html;
905 1067 }
906 1068
1069 + $handle_delayed = self::handle_delay_outcomes( $html );
1070 +
907 1071 $out = preg_replace_callback(
908 1072 '#<script\b([^>]*)>(.*?)</script>#is',
909 - static function ( array $m ): string {
1073 + static function ( array $m ) use ( $handle_delayed ): string {
910 1074 list( $whole, $attrs, $body ) = $m;
911 1075
912 1076 if ( '' === trim( $body ) ) {
913 1077 return $whole;
@@ -946,8 +1110,47 @@
946 1110 if ( false !== stripos( $body, 'document.write' ) ) {
947 1111 return $whole;
948 1112 }
949 1113
1114 + // Our own inline scripts, by the id they are printed with.
1115 + // The src passes get this for free from the handle prefix,
1116 + // but here the handle is '' — and the facade observer's body
1117 + // names youtube/vimeo, so a user target like "youtube" would
1118 + // park the very script that makes those embeds cheap.
1119 + if ( preg_match( '#(?<![-\w])id\s*=\s*(["\'])xspeed-#i', $attrs ) ) {
1120 + return $whole;
1121 + }
1122 +
1123 + // A handle's own inline blocks follow the handle, not only their
1124 + // body text. The body rule below decided them alone, so a
1125 + // `-js-extra` whose data named a target was parked while its
1126 + // script, kept eager by a URL exclusion, ran first and read an
1127 + // undefined global. (#549)
1128 + //
1129 + // Ahead of the exclusion list on purpose. The handle's own tag
1130 + // was already weighed against it by handle and URL; a body
1131 + // match here would keep the after-code of a delayed script
1132 + // eager, running it before the script it calls.
1133 + if ( preg_match( '#(?<![-\w])id\s*=\s*(["\'])(.+?)-js-(extra|before|after)\1#i', $attrs, $own ) ) {
1134 + $part = strtolower( $own[3] );
1135 + // wp_localize_script data. Early is always safe: it only
1136 + // assigns, and its script cannot run before it.
1137 + if ( 'extra' === $part ) {
1138 + return $whole;
1139 + }
1140 + if ( isset( $handle_delayed[ $own[2] ] ) ) {
1141 + if ( $handle_delayed[ $own[2] ] ) {
1142 + return '<script' . self::park_type_attrs( $attrs ) . '>' . $body . '</script>';
1143 + }
1144 + // The script runs at load, so its `before` code must too.
1145 + // Its `after` code still runs after it if parked, so that
1146 + // one is left to the body rule, like any vendor loader.
1147 + if ( 'before' === $part ) {
1148 + return $whole;
1149 + }
1150 + }
1151 + }
1152 +
950 1153 // The body stands in for the URL in the lists the src passes
951 1154 // consult — but NOT via is_delay_target(), whose empty-list
952 1155 // default is "delay everything". That default is right for a
953 1156 // tag with a URL and catastrophic here: it would park every
@@ -953,12 +1156,16 @@
953 1156 // tag with a URL and catastrophic here: it would park every
954 1157 // inline script on the page. Inline code is delayed only on a
955 1158 // positive identification — the body names a known vendor
956 1159 // host, or a fragment the user targeted — and the exclusion
957 - // list still wins first.
958 - if ( self::is_excluded_script( '', $body ) ) {
1160 + // list still wins first. A target naming a consent manager
1161 + // lifts the floor here the same way it does for a src tag;
1162 + // without it the same entry delayed the file and left the
1163 + // vendor's inline code eager.
1164 + if ( self::is_excluded_script( '', $body, true ) ) {
959 1165 return $whole;
960 1166 }
1167 +
961 1168 if ( ! self::matches_known_third_party( $body ) && ! self::matches_user_targets( $body ) ) {
962 1169 return $whole;
963 1170 }
964 1171
@@ -977,8 +1184,264 @@
977 1184 return null === $out ? $html : $out;
978 1185 }
979 1186
980 1187 /**
1188 + * Whether each enqueued handle's external tag ended up delayed.
1189 + *
1190 + * Read from the finished HTML rather than recorded as tags are filtered:
1191 + * this runs after every pass that can delay a tag (script_loader_tag, the
1192 + * late opt-out revert, the raw-tag sweep), so the page itself is the only
1193 + * complete answer.
1194 + *
1195 + * @param string $html Complete page HTML.
1196 + * @return array<string,bool> Handle => delayed.
1197 + */
1198 + private static function handle_delay_outcomes( string $html ): array {
1199 + if ( ! preg_match_all( '#<script\b((?:"[^"]*"|\'[^\']*\'|[^>"\'])*)>#i', $html, $m ) ) {
1200 + return array();
1201 + }
1202 + $out = array();
1203 + foreach ( $m[1] as $attrs ) {
1204 + if ( ! preg_match( '#(?<![-\w])id\s*=\s*(["\'])(.+?)-js\1#i', $attrs, $id ) ) {
1205 + continue;
1206 + }
1207 + $out[ $id[2] ] = false !== stripos( $attrs, 'data-xs-delay' ) || false !== stripos( $attrs, 'data-xs-src' );
1208 + }
1209 + return $out;
1210 + }
1211 +
1212 + /**
1213 + * What a held async sheet runs once it has settled: mark itself and let
1214 + * the flip script check whether every held sheet has.
1215 + */
1216 + private const HOLD_SETTLED_JS = "this.setAttribute('data-xs-ready','1');window.xsCssFlip&&xsCssFlip()";
1217 +
1218 + /**
1219 + * A held sheet that fails (404, blocked, network error) never fires
1220 + * `load`, so with only an onload the flip waited for it and every other
1221 + * sheet stayed off until the 5-second fallback: an unstyled page. An
1222 + * error settles it as well. An onerror the tag already carries keeps
1223 + * running, after ours, so its throwing cannot hold the flip back.
1224 + *
1225 + * @param string $tag A held `<link>` tag, already carrying our onload.
1226 + */
1227 + private static function settle_held_sheet_on_error( string $tag ): string {
1228 + $merged = (string) preg_replace_callback(
1229 + '#\sonerror\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s"\'>]+))#i',
1230 + static function ( array $e ): string {
1231 + $own = (string) ( $e[1] ?? '' ) . (string) ( $e[2] ?? '' ) . (string) ( $e[3] ?? '' );
1232 + $own = html_entity_decode( $own, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
1233 + return ' onerror="' . self::HOLD_SETTLED_JS . ';' . esc_attr( $own ) . '"';
1234 + },
1235 + $tag,
1236 + 1,
1237 + $count
1238 + );
1239 + if ( 1 === $count ) {
1240 + return $merged;
1241 + }
1242 + return (string) preg_replace(
1243 + '#\sonload="' . preg_quote( self::HOLD_SETTLED_JS, '#' ) . '"#',
1244 + '$0 onerror="' . self::HOLD_SETTLED_JS . '"',
1245 + $tag,
1246 + 1
1247 + );
1248 + }
1249 +
1250 + /**
1251 + * Hosts whose stylesheets are the site's own for the transition hold:
1252 + * the site's host and, when the CDN rewrite is on, its CDN host. A sheet
1253 + * from any other host applies on its own load.
1254 + *
1255 + * @return string[] Lowercase hosts.
1256 + */
1257 + private static function first_party_hosts(): array {
1258 + $hosts = array( strtolower( (string) wp_parse_url( home_url( '/' ), PHP_URL_HOST ) ) );
1259 + $cdn = get_option( 'xspeed_module_cdn', array() );
1260 + if ( is_array( $cdn ) && ! empty( $cdn['enabled'] ) && ! empty( $cdn['cdn_url'] ) ) {
1261 + $hosts[] = (string) preg_replace( '#[/:].*$#', '', Cdn_Rewriter::normalize_host( (string) $cdn['cdn_url'] ) );
1262 + }
1263 + /**
1264 + * Filter: xspeed_async_css_first_party_hosts. Hosts whose async
1265 + * stylesheets wait for the transition hold's single flip. Add a
1266 + * static-asset host that serves the site's own CSS.
1267 + *
1268 + * @param string[] $hosts Lowercase hosts.
1269 + */
1270 + $hosts = (array) apply_filters( 'xspeed_async_css_first_party_hosts', $hosts );
1271 + return array_values( array_filter( array_map( static fn( $h ) => strtolower( trim( (string) $h ) ), $hosts ) ) );
1272 + }
1273 +
1274 + /**
1275 + * Hold CSS transitions while async stylesheets load.
1276 + *
1277 + * Critical CSS styles only the first screen. When the deferred
1278 + * stylesheets arrive, every element that has a `transition` and a value
1279 + * that changes animates at once: below the fold from the browser's
1280 + * defaults, above it wherever the critical CSS differs. On an Elementor
1281 + * page that was about 100 elements and seconds of main-thread work on a
1282 + * throttled phone. Transitions stay off until the last async sheet has
1283 + * applied, then come back two frames later.
1284 + *
1285 + * @param string $html Complete page HTML.
1286 + */
1287 + public static function hold_transitions_for_async_css( $html ): string {
1288 + if ( ! is_string( $html ) || '' === $html ) {
1289 + return (string) $html;
1290 + }
1291 + if ( self::skip_in_non_frontend_context() ) {
1292 + return $html;
1293 + }
1294 + /**
1295 + * Filter: xspeed_async_css_hold_transitions. Return false to let
1296 + * transitions run while async stylesheets load.
1297 + *
1298 + * @param bool $hold Whether to hold them. Default true.
1299 + */
1300 + if ( ! apply_filters( 'xspeed_async_css_hold_transitions', true ) ) {
1301 + return $html;
1302 + }
1303 + if ( false !== strpos( $html, 'id="xspeed-transition-hold-js"' ) ) {
1304 + return $html;
1305 + }
1306 + if ( ! preg_match( '#<link\b[^>]*\bdata-(?:xs|xspeed)-async\b#i', $html ) ) {
1307 + return $html;
1308 + }
1309 + // Async sheets used to switch themselves on as each finished, in
1310 + // download order. Between the first and the last the page ran on a
1311 + // partial cascade that matched neither the critical CSS nor the
1312 + // final layout, and the hero jumped (CLS 0.3 on a phone). Each sheet
1313 + // now only marks itself loaded; the script below switches them all
1314 + // on together, in document order, once every one has loaded.
1315 + // A cross-origin sheet (Google Fonts, a CDN font kit) keeps switching
1316 + // itself on: waiting for it let a slow third party hold back the
1317 + // site's own CSS. The flip script skips it too.
1318 + $own_hosts = self::first_party_hosts();
1319 + $rewritten = (string) preg_replace_callback(
1320 + '#<link\b[^>]*\bdata-(?:xs|xspeed)-async\b[^>]*>#i',
1321 + static function ( array $m ) use ( $own_hosts ): string {
1322 + if ( preg_match( '#\shref\s*=\s*["\']?(?:https?:)?//([^/"\'\s>:]+)#i', $m[0], $h ) && ! in_array( strtolower( $h[1] ), $own_hosts, true ) ) {
1323 + return $m[0];
1324 + }
1325 + $held = (string) preg_replace(
1326 + '#\sonload\s*=\s*"this\.media=\'[^\'"]*\'"#i',
1327 + ' data-xs-hold="1" onload="' . self::HOLD_SETTLED_JS . '"',
1328 + $m[0],
1329 + 1,
1330 + $count
1331 + );
1332 + if ( 1 !== $count ) {
1333 + return $m[0];
1334 + }
1335 + return self::settle_held_sheet_on_error( $held );
1336 + },
1337 + $html
1338 + );
1339 +
1340 + // The hold style is added by a script, so a visitor without
1341 + // JavaScript, whom the flip script never reaches, keeps transitions:
1342 + // a style in the markup stayed for good there. The no-JS page is the
1343 + // page without this pass, apart from the inert script tags.
1344 + $style = '<script id="xspeed-transition-hold-css">(function(){var s=document.createElement("style");s.id="xspeed-transition-hold";'
1345 + . 's.textContent="*,*::before,*::after{transition:none!important}";(document.head||document.documentElement).appendChild(s)})();</script>';
1346 + $script = '<script id="xspeed-transition-hold-js">(function(){var s=document.getElementById("xspeed-transition-hold"),d=0,dcl=0;'
1347 + . 'function links(){return document.querySelectorAll("link[data-xs-hold]")}'
1348 + . 'function flip(force){if(d)return;var l=links(),i;if(!force){if(!dcl)return;for(i=0;i<l.length;i++)if(l[i].media==="print"&&!l[i].hasAttribute("data-xs-ready"))return}'
1349 + . 'd=1;for(i=0;i<l.length;i++)if(l[i].media==="print")l[i].media=l[i].getAttribute("data-xs-async")||l[i].getAttribute("data-xspeed-async")||"all";'
1350 + . 'requestAnimationFrame(function(){requestAnimationFrame(function(){s&&s.parentNode&&s.parentNode.removeChild(s)})})}'
1351 + . 'window.xsCssFlip=function(){flip(0)};'
1352 + . 'document.addEventListener("DOMContentLoaded",function(){dcl=1;flip(0)});setTimeout(function(){flip(1)},5000)})();</script>';
1353 +
1354 + $out = preg_replace( '#<head\b[^>]*>#i', '$0' . $style, $rewritten, 1, $count );
1355 + if ( null === $out || 1 !== $count ) {
1356 + return $html;
1357 + }
1358 + $with_script = preg_replace( '#</body>#i', $script . '$0', $out, 1, $count );
1359 + return ( null === $with_script || 1 !== $count ) ? $html : $with_script;
1360 + }
1361 +
1362 + /**
1363 + * Action: `wp_head` (priority 1). Show Elementor's entrance-animation
1364 + * elements when Delay JS holds back the script that would show them.
1365 + *
1366 + * Elementor prints a widget with an entrance animation as
1367 + * `elementor-invisible` (visibility:hidden), and its frontend script
1368 + * removes the class as the widget scrolls into view. Delayed, that script
1369 + * runs on the first interaction, so a hero with an entrance animation
1370 + * stayed blank until then. Lighthouse never interacts: it measured an
1371 + * empty first screen, and its LCP and CLS described a page nobody sees.
1372 + *
1373 + * Printed from the head rather than the cached-page buffer, which never
1374 + * runs with the page cache off or on a bypassed page, where the script
1375 + * is delayed all the same. The decision is the one delay_script_tag()
1376 + * makes later in the request: Smart Delay delays the handle unless it is
1377 + * excluded; plain delay keeps it live (its config snippet reads it)
1378 + * unless the user named it. A rule left on a page with no such element
1379 + * matches nothing.
1380 + */
1381 + public static function print_entrance_animation_reveal(): void {
1382 + if ( self::skip_in_non_frontend_context() || ! self::delays_elementor_frontend() ) {
1383 + return;
1384 + }
1385 + /**
1386 + * Filter: xspeed_delay_js_reveal_entrance_animations. Return false to
1387 + * keep Elementor's entrance-animation elements hidden until the
1388 + * delayed frontend script runs.
1389 + *
1390 + * @param bool $reveal Whether to show them at load. Default true.
1391 + */
1392 + if ( ! apply_filters( 'xspeed_delay_js_reveal_entrance_animations', true ) ) {
1393 + return;
1394 + }
1395 + echo self::entrance_reveal_markup() . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- fixed markup, no input.
1396 + }
1397 +
1398 + /**
1399 + * The reveal style, and the script that settles what the visitor has
1400 + * already seen.
1401 + *
1402 + * Shown by the style, an element still carries its entrance animation,
1403 + * and when the delayed frontend script runs Elementor plays it: the
1404 + * element drops to opacity 0 and fades back in. For the first screen that
1405 + * was the hero heading vanishing on the first mouse move. So when the
1406 + * replay starts (`xspeed:replaying`, before any delayed script is back),
1407 + * every animated element in the viewport has its animation set to
1408 + * `none` in `data-settings`, which Elementor reads as "show it, do not
1409 + * animate". Elements further down keep theirs and animate as they
1410 + * scroll in, as on a page without Delay JS.
1411 + */
1412 + public static function entrance_reveal_markup(): string {
1413 + return '<style id="xspeed-reveal-entrance">.elementor-invisible{visibility:visible!important}</style>'
1414 + . '<script id="xspeed-reveal-entrance-js" data-xs-nodelay>document.addEventListener("xspeed:replaying",function(){'
1415 + . 'var h=window.innerHeight,w=window.innerWidth,j=window.jQuery;'
1416 + . 'Array.prototype.forEach.call(document.querySelectorAll(".elementor-invisible[data-settings]"),function(e){'
1417 + . 'var r=e.getBoundingClientRect(),s,k;'
1418 + . 'if(!(r.width||r.height)||r.bottom<=0||r.top>=h||r.right<=0||r.left>=w)return;'
1419 + . 'try{s=JSON.parse(e.getAttribute("data-settings"))}catch(x){return}'
1420 + . 'if(!s||typeof s!=="object")return;'
1421 + . 'for(k in s)if(/^_?animation(_|$)/.test(k)&&!/(delay|duration)/.test(k))s[k]="none";'
1422 + . 'e.setAttribute("data-settings",JSON.stringify(s));e.classList.remove("elementor-invisible");'
1423 + . 'j&&j.removeData&&j.removeData(e,"settings")})},{once:true})</script>';
1424 + }
1425 +
1426 + /** Will Delay JS hold back Elementor's frontend script on this request? */
1427 + private static function delays_elementor_frontend(): bool {
1428 + $opts = self::opts();
1429 + if ( empty( $opts['delay_js'] ) ) {
1430 + return false;
1431 + }
1432 + $handle = 'elementor-frontend';
1433 + $src = self::registered_src( $handle );
1434 + if ( '' === $src ) {
1435 + return false; // Elementor is not loaded.
1436 + }
1437 + if ( self::smart_delay_enabled() ) {
1438 + return self::smart_delays_handle( $handle );
1439 + }
1440 + return ! self::is_excluded_script( $handle, $src, true ) && self::is_user_named_target( $handle, $src );
1441 + }
1442 +
1443 + /**
981 1444 * Inline bootstrap that flips delayed scripts on the first user
982 1445 * interaction. Printed once on wp_footer priority 1000.
983 1446 */
984 1447 public static function print_delay_bootstrap(): void {
@@ -998,70 +1461,49 @@
998 1461 $opts = self::opts();
999 1462 $timeout = isset( $opts['delay_js_timeout'] ) ? (int) $opts['delay_js_timeout'] : 8000;
1000 1463 $timeout = max( 0, min( 60000, $timeout ) );
1001 1464
1002 - // Tiny vanilla bootstrap; keep it self-contained so the page
1003 - // has no JS dependencies before the first interaction.
1004 - ?>
1005 -<script id="xspeed-delay-bootstrap">
1006 -(function(){
1007 - var events=['mousemove','keydown','touchstart','scroll','wheel'];
1008 - var fired=false;
1009 - function load(){
1010 - if(fired)return;fired=true;
1011 - events.forEach(function(e){window.removeEventListener(e,load,{passive:true,capture:true});});
1012 - var delayed=document.querySelectorAll('script[data-xs-delay]');
1013 - delayed.forEach(function(s){
1014 - var n=document.createElement('script');
1015 - // A dynamically-created script is async by default, so replayed
1016 - // EXTERNALS would race each other; async=false restores document
1017 - // order among the externals. Narrower guarantee, stated plainly:
1018 - // a replayed INLINE script still executes synchronously at its
1019 - // replaceChild, i.e. possibly before an earlier external has
1020 - // finished LOADING — so an inline consumer of a delayed external
1021 - // is only safe when both were delayed by explicit user targeting
1022 - // (the inline-bound guard keeps the implicit case eager).
1023 - n.async=false;
1024 - // Nonce hiding: a connected element's nonce CONTENT attribute reads
1025 - // as "", so copying it via the attribute loop would hand the clone
1026 - // an empty nonce and a nonce-based CSP would block the replay. The
1027 - // IDL property still carries the real value.
1028 - if(s.nonce){n.nonce=s.nonce;}
1029 - Array.prototype.slice.call(s.attributes).forEach(function(a){
1030 - if(a.name==='data-xs-src'){n.setAttribute('src',a.value);return;}
1031 - if(a.name==='data-xs-delay')return;
1032 - if(a.name==='nonce')return;
1033 - // A parked inline tag's ORIGINAL type (module, mostly) rides in
1034 - // data-xs-type — restore it, or the replay runs a module as a
1035 - // classic script and its imports throw. (#274)
1036 - if(a.name==='data-xs-type'){n.setAttribute('type',a.value);return;}
1037 - // `type` is what a script IS, not decoration, so it is carried over
1038 - // — with ONE exception: our own inline parking marker, which exists
1039 - // only to stop the browser executing the original and must not be
1040 - // copied onto the replacement. Dropping type wholesale broke two
1041 - // things: `type="module"` became a classic script (core's Script
1042 - // Modules — Navigation, lightbox, Query Loop — threw "Cannot use
1043 - // import statement outside a module" on the default theme), and
1044 - // `type="text/plain"`, which is precisely how a consent manager
1045 - // parks a blocked third-party script, became executable again. The
1046 - // second is a privacy failure, not a broken feature. (#274)
1047 - if(a.name==='type'&&a.value==='text/xspeed-delayed')return;
1048 - n.setAttribute(a.name,a.value);
1049 - });
1050 - if(!s.hasAttribute('data-xs-src')){n.text=s.text;}
1051 - s.parentNode.replaceChild(n,s);
1052 - });
1053 - }
1054 - events.forEach(function(e){window.addEventListener(e,load,{passive:true,capture:true});});
1055 -<?php if ( $timeout > 0 ) : ?>
1056 - setTimeout(load,<?php echo (int) $timeout; ?>);
1057 -<?php endif; ?>
1058 -})();
1059 -</script>
1060 - <?php
1465 + // The script is includes/js/delay-bootstrap.js, which also carries
1466 + // the design notes for the lifecycle replay (#494). `npm run build`
1467 + // minifies it into assets/delay-bootstrap.min.js; the timeout goes in
1468 + // place of its one placeholder.
1469 + //
1470 + // The tag goes out through wp_print_inline_script_tag(), like Free's
1471 + // other inline scripts, so a CSP plugin's wp_inline_script_attributes
1472 + // filter can give it a nonce. Printed bare, a nonce CSP blocked it
1473 + // and nothing was ever replayed.
1474 + $js = str_replace( 'XSPEED_DELAY_TIMEOUT', (string) $timeout, self::delay_bootstrap_js() );
1475 + wp_print_inline_script_tag( $js, array( 'id' => 'xspeed-delay-bootstrap' ) );
1061 1476 }
1062 1477
1478 + /** The delay bootstrap's code, read once per request. */
1479 + private static $delay_bootstrap_js = null;
1480 +
1063 1481 /**
1482 + * The built delay bootstrap, without the line that records its source.
1483 + * If the build is missing, the readable source is valid JS too, only
1484 + * larger: printing nothing would leave every delayed script parked for
1485 + * good, because the tags are already rewritten by the time this runs.
1486 + */
1487 + private static function delay_bootstrap_js(): string {
1488 + if ( null !== self::$delay_bootstrap_js ) {
1489 + return self::$delay_bootstrap_js;
1490 + }
1491 + $root = dirname( __DIR__ );
1492 + $built = $root . '/assets/delay-bootstrap.min.js';
1493 + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- a local plugin file, not a remote URL.
1494 + $js = is_readable( $built ) ? (string) file_get_contents( $built ) : '';
1495 + if ( '' !== $js ) {
1496 + $js = (string) preg_replace( '#\A/\*[^\n]*\*/\n#', '', $js );
1497 + } else {
1498 + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- a local plugin file, not a remote URL.
1499 + $js = (string) file_get_contents( $root . '/includes/js/delay-bootstrap.js' );
1500 + }
1501 + self::$delay_bootstrap_js = trim( $js );
1502 + return self::$delay_bootstrap_js;
1503 + }
1504 +
1505 + /**
1064 1506 * Filter: `style_loader_tag` — wrap stylesheets in the
1065 1507 * print → onload="all" pattern so they download non-blocking.
1066 1508 * Pairs with critical CSS workflows. Adds a <noscript> fallback so
1067 1509 * users with JS disabled still get styles applied (via media="all").
@@ -1081,8 +1523,21 @@
1081 1523 // want to fight with explicit author intent.
1082 1524 if ( false === stripos( $tag, 'rel=\'stylesheet\'' ) && false === stripos( $tag, 'rel="stylesheet"' ) ) {
1083 1525 return $tag;
1084 1526 }
1527 + // No critical CSS for this page: every stylesheet stays blocking.
1528 + //
1529 + // Deferring a stylesheet only helps when something already styles the
1530 + // first screen. Without that, the page paints unstyled and then jumps
1531 + // when the sheets arrive. Measured on the Templately Astoria pages
1532 + // (Elementor and a block theme): CLS 0.43-1.27 and 15-43 points lower
1533 + // on 7 of 8 pages than the same settings without async CSS. The guards
1534 + // below narrow the damage; this one removes it. WP Rocket, LiteSpeed,
1535 + // Jetpack Boost and FlyingPress likewise never defer CSS without
1536 + // critical CSS. (#588)
1537 + if ( ! self::page_has_critical_css() ) {
1538 + return $tag;
1539 + }
1085 1540 // The stylesheets that lay the page out stay render-blocking.
1086 1541 //
1087 1542 // This transform moves a sheet to AFTER first paint. That is the
1088 1543 // point of it — but a sheet the layout depends on is then missing
@@ -1389,12 +1844,19 @@
1389 1844 * than a hard-coded list.
1390 1845 * - WordPress' own BLOCK and layout sheets (`wp-block-library`,
1391 1846 * `global-styles`, `classic-theme-styles`). These style block
1392 1847 * content on the front end and are as structural as the theme's.
1848 + * - A page builder's GRID sheets: the rows, columns, sections and
1849 + * containers everything else sits in (`kadence-blocks-rowlayout`,
1850 + * `kadence-blocks-column`, `elementor-frontend`, `elementor-post-N`).
1851 + * On a builder page these lay out the hero, not the theme. Deferred,
1852 + * the hero painted as one stacked column and then snapped into its
1853 + * grid: CLS 0.665 on desktop, from one row.
1393 1854 *
1394 - * Everything else — plugin sheets, icon fonts, widget and page-builder
1395 - * add-ons, the long tail that makes async CSS worth having — is still
1396 - * deferred, so the optimization keeps most of its benefit.
1855 + * Everything else — plugin sheets, icon fonts, buttons, forms, the
1856 + * builder's per-widget sheets, the long tail that makes async CSS worth
1857 + * having — is still deferred, so the optimization keeps most of its
1858 + * benefit.
1397 1859 *
1398 1860 * A site WITH critical CSS can defer these too; that is what the
1399 1861 * `xspeed_async_css_layout_critical` filter is for.
1400 1862 *
@@ -1411,19 +1873,21 @@
1411 1873 'wp-block-library-theme',
1412 1874 'global-styles',
1413 1875 'classic-theme-styles',
1414 1876 );
1415 - $critical = in_array( $handle, $core, true );
1877 + $critical = in_array( $handle, $core, true ) || self::is_builder_grid_style( $handle );
1416 1878
1417 1879 // The active theme's own sheets.
1418 1880 //
1419 1881 // Matched on the theme stem, but NOT as a bare prefix: a plugin from
1420 1882 // the same vendor shares it (the Kadence theme is `kadence`, while
1421 - // `kadence-blocks-rowlayout` and `kadence-fonts-gfonts` come from the
1422 - // Kadence Blocks PLUGIN and a webfont loader). Treating those as
1423 - // layout-critical would leave almost nothing deferred and quietly
1424 - // undo the feature. So the stem must be followed by a recognised
1425 - // theme-area segment, which is how themes name their split sheets.
1883 + // `kadence-blocks-image` and `kadence-fonts-gfonts` come from the
1884 + // Kadence Blocks PLUGIN and a webfont loader). Treating every such
1885 + // sheet as layout-critical would leave almost nothing deferred and
1886 + // quietly undo the feature; the builder's grid sheets are caught
1887 + // above by what they do, not whose they are. So the stem must be
1888 + // followed by a recognised theme-area segment, which is how themes
1889 + // name their split sheets.
1426 1890 if ( ! $critical && function_exists( 'get_template' ) ) {
1427 1891 $areas = array(
1428 1892 'style',
1429 1893 'global',
@@ -1468,8 +1932,28 @@
1468 1932 return (bool) apply_filters( 'xspeed_async_css_layout_critical', $critical, $handle );
1469 1933 }
1470 1934
1471 1935 /**
1936 + * Whether a handle is a page builder's grid sheet.
1937 + *
1938 + * Matched on the last segment of the handle, so a builder that names its
1939 + * row sheet `acme-blocks-row-layout` is covered without being listed. The
1940 + * segments are the ones that only ever carry structure; a button, image
1941 + * or form sheet styles an element inside the grid, and the grid holds its
1942 + * place while that sheet loads.
1943 + *
1944 + * @param string $handle Lowercase stylesheet handle.
1945 + */
1946 + private static function is_builder_grid_style( string $handle ): bool {
1947 + if ( preg_match( '#(?:^|-)(?:rowlayout|row-layout|column|columns|container|section|grid)$#', $handle ) ) {
1948 + return true;
1949 + }
1950 + // Builders whose grid lives in a sheet named after the builder or the
1951 + // post, not after a structural element.
1952 + return (bool) preg_match( '#^(?:elementor-frontend|elementor-post-\d+|fl-builder-layout(?:-\d+)?|generateblocks)$#', $handle );
1953 + }
1954 +
1955 + /**
1472 1956 * Filter: `style_loader_src` + `script_loader_src` — strip the
1473 1957 * ?ver=X.Y query string that WP appends for cache busting. Some
1474 1958 * CDNs / reverse proxies cache better when the URL has no query.
1475 1959 *
@@ -1670,9 +2154,201 @@
1670 2154 'wp-url',
1671 2155 'wp-api-fetch',
1672 2156 );
1673 2157
1674 - private static function is_excluded_script( string $handle, string $src ): bool {
2158 + /**
2159 + * Consent managers are never deferred, and never delayed by a broad
2160 + * setting — only a delay_js_targets entry that NAMES the vendor lifts
2161 + * the floor (see user_named_consent_manager()); the
2162 + * `xspeed_js_exclusion_floor` filter remains the code-level override.
2163 + *
2164 + * A consent banner is drawn by JavaScript, and it is the one thing on
2165 + * the page that has to appear before anything else happens. Delay it
2166 + * and a visitor who lands, reads and leaves without touching the page
2167 + * is never asked — on an opt-in configuration the site then ran
2168 + * without ever offering the choice.
2169 + *
2170 + * The editable list cannot carry this. A stored value replaces the
2171 + * schema default outright (Settings_Manager::get()), so widening that
2172 + * default would reach fresh installs only, and clearing the textarea
2173 + * would drop the protection again. Same floor pattern as
2174 + * Server_Rules::COOKIE_FLOOR. Trim or extend it through
2175 + * `xspeed_js_exclusion_floor`.
2176 + *
2177 + * A URL token cannot survive a rewrite of that URL: Minify JS rewrites a
2178 + * local script to a hashed /cache/xspeed/min/ path, and Combine JS folds
2179 + * it into a bundle. On the enqueue path original_src() gives the pre-minify
2180 + * URL back, but the buffer sweep has only the tag -- so with Minify JS on
2181 + * and the `id` stripped, a banner shipped un-minified is not recognised.
2182 + * Documented in docs/user/minification.md rather than papered over.
2183 + *
2184 + * Each entry goes through target_matches(): an exact handle OR a
2185 + * case-insensitive URL substring. Both passes can match either — the
2186 + * enqueue path is handed the handle, and the buffer sweep reads it back
2187 + * out of the tag's `id`. A URL token additionally covers a banner that
2188 + * was never enqueued at all, which is how Cookiebot prints itself. (#275)
2189 + */
2190 + private const CONSENT_MANAGER_FLOOR = array(
2191 + // Prefer a plugin-directory or vendor-host URL token over a handle.
2192 + // A handle is only readable on the enqueue path and, on the buffer
2193 + // sweep, only if the tag still carries the `id` WordPress prints —
2194 + // which another plugin can strip. A URL token matches on both passes
2195 + // and covers a banner that was never enqueued at all. (#275 QA)
2196 +
2197 + // CookieYes / GDPR Cookie Consent. Handle and plugin directory are
2198 + // the same string, so this covers both paths.
2199 + 'cookie-law-info',
2200 + // Complianz: the plugin directory, covering -gdpr and -gdpr-premium.
2201 + // Was the `cmplz-cookiebanner` handle, which needed the `id` tag.
2202 + 'complianz',
2203 + // NotificationX runs its GDPR cookie notice off the same handle as
2204 + // every other notification, so excluding it excludes them all. That
2205 + // is what the plugin's own team asked for. Directory token covers
2206 + // the Pro build too; was the `notificationx-public` handle.
2207 + 'notificationx',
2208 + // Cookiebot prints its loader straight into wp_head, so only the
2209 + // buffer sweep ever sees it. This is the token Cookiebot's own WP
2210 + // Rocket and LiteSpeed integrations exclude.
2211 + 'consent.cookiebot.com',
2212 + // Cookie Notice — named in the original report and one of the most
2213 + // installed consent plugins. Its banner is enqueued from
2214 + // /plugins/cookie-notice/js/front.min.js.
2215 + 'cookie-notice',
2216 + // Cookie Notice in Cookie Compliance mode prints a different loader,
2217 + // whose host is overridable via CN_APP_WIDGET_URL — so key on the
2218 + // filename, not the CDN host.
2219 + 'hu-banner',
2220 + // Moove GDPR Cookie Compliance. Directory token: its handle
2221 + // (`moove_gdpr_frontend`) does not appear in its own URL.
2222 + 'gdpr-cookie-compliance',
2223 + // Termly's resource blocker, which also covers the legacy embed.
2224 + 'app.termly.io',
2225 + // Usercentrics, reached three ways: Cookiebot's UC mode
2226 + // (web.cmp.usercentrics.eu), Termageddon (app.usercentrics.eu) and
2227 + // the privacy proxy.
2228 + 'usercentrics.eu',
2229 + // Iubenda: both the consent solution and the consent database SDK.
2230 + 'cdn.iubenda.com',
2231 + // OneTrust. Pasted snippet rather than a wordpress.org plugin, so
2232 + // this is the SDK host rather than a verified plugin path.
2233 + 'cdn.cookielaw.org',
2234 + // Borlabs is commercial and renames its files per release; the
2235 + // vendor's own guidance is that this string stays in every path.
2236 + 'borlabs-cookie',
2237 + // Real Cookie Banner, free and pro. Its anti-adblock mode serves the
2238 + // banner from an anonymised path that no URL token can match — use
2239 + // `xspeed_js_exclusion_floor` to add the handle on such a site.
2240 + 'real-cookie-banner',
2241 + // SureCookie.
2242 + 'surecookie',
2243 + );
2244 +
2245 + /**
2246 + * What a site owner types to name each floor entry, and what the admin
2247 + * shows them. Keyed by CONSENT_MANAGER_FLOOR token; a test holds the two
2248 + * in step.
2249 + *
2250 + * The keyword is the part of the token a person would actually write
2251 + * (`cookiebot`, not `consent.cookiebot.com`), and it is always a substring
2252 + * of the token, so an entry that names the vendor this way still matches
2253 + * the vendor's URL. A brand name that appears nowhere in the URL
2254 + * (`cookieyes`, `onetrust`, `cmplz`) is deliberately not a keyword: it
2255 + * could never match the tag, so offering it would promise a lift that
2256 + * cannot happen. The exact handle always works as well.
2257 + *
2258 + * Cookiebot in Usercentrics CMP mode loads from web.cmp.usercentrics.eu,
2259 + * so the floor catches it as Usercentrics and `usercentrics` names it,
2260 + * not `cookiebot`.
2261 + */
2262 + private const CONSENT_MANAGER_NAMES = array(
2263 + 'cookie-law-info' => array( 'label' => 'CookieYes', 'keyword' => 'cookie-law-info' ),
2264 + 'complianz' => array( 'label' => 'Complianz', 'keyword' => 'complianz' ),
2265 + 'notificationx' => array( 'label' => 'NotificationX', 'keyword' => 'notificationx' ),
2266 + 'consent.cookiebot.com' => array( 'label' => 'Cookiebot', 'keyword' => 'cookiebot' ),
2267 + 'cookie-notice' => array( 'label' => 'Cookie Notice', 'keyword' => 'cookie-notice' ),
2268 + 'hu-banner' => array( 'label' => 'Cookie Notice (Cookie Compliance)', 'keyword' => 'hu-banner' ),
2269 + 'gdpr-cookie-compliance' => array( 'label' => 'GDPR Cookie Compliance (Moove)', 'keyword' => 'gdpr-cookie-compliance' ),
2270 + 'app.termly.io' => array( 'label' => 'Termly', 'keyword' => 'termly' ),
2271 + 'usercentrics.eu' => array( 'label' => 'Usercentrics', 'keyword' => 'usercentrics' ),
2272 + 'cdn.iubenda.com' => array( 'label' => 'Iubenda', 'keyword' => 'iubenda' ),
2273 + 'cdn.cookielaw.org' => array( 'label' => 'OneTrust', 'keyword' => 'cookielaw' ),
2274 + 'borlabs-cookie' => array( 'label' => 'Borlabs Cookie', 'keyword' => 'borlabs' ),
2275 + 'real-cookie-banner' => array( 'label' => 'Real Cookie Banner', 'keyword' => 'real-cookie-banner' ),
2276 + 'surecookie' => array( 'label' => 'SureCookie', 'keyword' => 'surecookie' ),
2277 + );
2278 +
2279 + /**
2280 + * "Label (keyword)" for every built-in consent manager, for the admin.
2281 + *
2282 + * Reads the built-in list, not the filtered floor: the admin describes
2283 + * what ships, and a site that trimmed the floor in code knows it did.
2284 + *
2285 + * @return string[]
2286 + */
2287 + public static function consent_manager_labels(): array {
2288 + $out = array();
2289 + foreach ( self::CONSENT_MANAGER_FLOOR as $token ) {
2290 + $name = self::CONSENT_MANAGER_NAMES[ $token ] ?? array(
2291 + 'label' => $token,
2292 + 'keyword' => $token,
2293 + );
2294 + $out[] = $name['label'] . ' (' . $name['keyword'] . ')';
2295 + }
2296 + return $out;
2297 + }
2298 +
2299 + /**
2300 + * Per-request memo for exclusion_floor(). Null = not resolved.
2301 + *
2302 + * @var string[]|null
2303 + */
2304 + private static $exclusion_floor = null;
2305 +
2306 + /**
2307 + * The built-in exclusion floor, after the site has had its say.
2308 + *
2309 + * @return string[]
2310 + */
2311 + private static function exclusion_floor(): array {
2312 + if ( null === self::$exclusion_floor ) {
2313 + /**
2314 + * Scripts that are never deferred or delayed, whatever the
2315 + * user's exclusion list holds. Each entry is an exact script
2316 + * handle or a case-insensitive URL substring.
2317 + *
2318 + * Return the array minus a token to let Delay JS postpone that
2319 + * consent manager on purpose; add one to protect another script.
2320 + *
2321 + * @param string[] $floor Built-in floor.
2322 + */
2323 + $floor = apply_filters( 'xspeed_js_exclusion_floor', self::CONSENT_MANAGER_FLOOR );
2324 + self::$exclusion_floor = array_values(
2325 + array_filter( array_map( 'strval', (array) $floor ), static fn( $t ) => '' !== $t )
2326 + );
2327 + }
2328 + return self::$exclusion_floor;
2329 + }
2330 +
2331 + /**
2332 + * @param string $handle Script handle ('' on the buffer sweep
2333 + * when no id survived).
2334 + * @param string $src Script URL.
2335 + * @param bool $named_lifts_floor Delay paths only: a delay_js_targets
2336 + * entry that NAMES the consent manager
2337 + * passes the floor (see
2338 + * user_named_consent_manager()). Typing a
2339 + * consent manager's name into an
2340 + * allow-list is the site owner taking the
2341 + * consent-timing decision back — GDPR is
2342 + * theirs to weigh, not ours; the floor
2343 + * only exists so Delay JS can't hide a
2344 + * banner NOBODY pointed at. Their own
2345 + * exclusion list, ALWAYS_EXCLUDED_HANDLES
2346 + * and our beacons still win: on a
2347 + * conflict between the user's two lists,
2348 + * protection beats postponement.
2349 + */
2350 + private static function is_excluded_script( string $handle, string $src, bool $named_lifts_floor = false ): bool {
1675 2351 if ( in_array( $handle, self::ALWAYS_EXCLUDED_HANDLES, true ) ) {
1676 2352 return true;
1677 2353 }
1678 2354 // Never defer or delay our own scripts. The fold and RUM beacons
@@ -1685,8 +2361,24 @@
1685 2361 // beacon added later cannot re-open the hole.
1686 2362 if ( 0 === strpos( $handle, 'xspeed-' ) ) {
1687 2363 return true;
1688 2364 }
2365 + // Ahead of the user list, and ahead of the empty-list early return
2366 + // below: an install that saved the Minify panel before this shipped
2367 + // has a stored list that knows nothing about consent managers, and
2368 + // one that cleared the textarea has no list at all. Neither may
2369 + // hide the banner. (#275)
2370 + foreach ( self::exclusion_floor() as $needle ) {
2371 + if ( self::floor_matches( $needle, $handle, $src ) ) {
2372 + // `continue`, not `break`: a second floor token matching the
2373 + // same tag has to be named too, or a filter-added token
2374 + // would be lifted by an entry that names only the first.
2375 + if ( $named_lifts_floor && self::user_named_consent_manager( $needle, $handle, $src ) ) {
2376 + continue;
2377 + }
2378 + return true;
2379 + }
2380 + }
1689 2381 $opts = self::opts();
1690 2382 $excluded = is_array( $opts['defer_js_excluded'] ?? null ) ? $opts['defer_js_excluded'] : array();
1691 2383 if ( empty( $excluded ) ) {
1692 2384 return false;
@@ -1702,8 +2394,56 @@
1702 2394 return false;
1703 2395 }
1704 2396
1705 2397 /**
2398 + * target_matches() for a floor token, with the site's own host removed
2399 + * from the URL first.
2400 + *
2401 + * Floor tokens are plugin names, and a plugin's own website is often
2402 + * named after the plugin. On notificationx.com the `notificationx` token
2403 + * matched every same-origin script URL, so Defer JS and Delay JS skipped
2404 + * every script on the site. The path still matches, so a script under
2405 + * /plugins/notificationx/ keeps its protection, and a third-party host
2406 + * such as consent.cookiebot.com still matches in full.
2407 + *
2408 + * @param string $needle Floor token.
2409 + * @param string $handle Script handle.
2410 + * @param string $src Script URL.
2411 + */
2412 + private static function floor_matches( string $needle, string $handle, string $src ): bool {
2413 + if ( '' === $needle ) {
2414 + return false;
2415 + }
2416 + if ( $handle === $needle ) {
2417 + return true;
2418 + }
2419 + foreach ( array( $src, self::original_src( $handle ) ) as $url ) {
2420 + $url = self::without_own_host( $url );
2421 + if ( '' !== $url && false !== stripos( $url, $needle ) ) {
2422 + return true;
2423 + }
2424 + }
2425 + return false;
2426 + }
2427 +
2428 + /**
2429 + * The URL without its scheme and host when the host is the site's own.
2430 + * Any other URL comes back unchanged.
2431 + *
2432 + * @param string $url Script URL.
2433 + */
2434 + private static function without_own_host( string $url ): string {
2435 + if ( '' === $url || ! function_exists( 'home_url' ) ) {
2436 + return $url;
2437 + }
2438 + $host = (string) wp_parse_url( home_url(), PHP_URL_HOST );
2439 + if ( '' === $host ) {
2440 + return $url;
2441 + }
2442 + return (string) preg_replace( '#^(?:https?:)?//' . preg_quote( $host, '#' ) . '(?::\d+)?(?=[/?\#]|$)#i', '', $url );
2443 + }
2444 +
2445 + /**
1706 2446 * Include-list targeting for delay (issue #36): when delay_js_targets
1707 2447 * is non-empty, ONLY matching scripts are delayed — a heavy
1708 2448 * third-party embed can be postponed without delaying the whole
1709 2449 * page's JS. Empty targets = historical behavior (delay everything
@@ -1753,8 +2493,203 @@
1753 2493 }
1754 2494 return false;
1755 2495 }
1756 2496
2497 + /**
2498 + * Whether a delay_js_targets entry NAMES the consent manager whose floor
2499 + * token matched this tag, and so lifts the floor for it.
2500 + *
2501 + * is_user_named_target() is not enough here: it asks whether any entry
2502 + * matches the tag, and a delay target is a URL substring. `/plugins/`,
2503 + * `.js`, `min.js`, `frontend` or the site's own host each match every
2504 + * consent banner on the page, so one broad entry switched the floor off
2505 + * for all of them and brought #275 back. An entry names the vendor when
2506 + * it is the exact handle, or when it contains the vendor's keyword (or
2507 + * its floor token) and still matches the tag, so `notificationx` and
2508 + * `/plugins/notificationx/` lift NotificationX, `termly` cannot lift
2509 + * Cookiebot, and `/plugins/` lifts nothing.
2510 + *
2511 + * A token added through `xspeed_js_exclusion_floor` has no keyword, so
2512 + * only an entry containing that token, or the exact handle, names it.
2513 + *
2514 + * @param string $floor_token The floor entry that matched this tag.
2515 + * @param string $handle Script handle ('' when unknown).
2516 + * @param string $src Script URL, or the body on the inline pass.
2517 + */
2518 + private static function user_named_consent_manager( string $floor_token, string $handle, string $src ): bool {
2519 + $opts = self::opts();
2520 + $targets = is_array( $opts['delay_js_targets'] ?? null ) ? $opts['delay_js_targets'] : array();
2521 + $names = array( $floor_token );
2522 + if ( isset( self::CONSENT_MANAGER_NAMES[ $floor_token ] ) ) {
2523 + $names[] = self::CONSENT_MANAGER_NAMES[ $floor_token ]['keyword'];
2524 + }
2525 + foreach ( $targets as $needle ) {
2526 + $needle = trim( (string) $needle );
2527 + if ( '' === $needle ) {
2528 + continue;
2529 + }
2530 + $names_it = '' !== $handle && $handle === $needle;
2531 + foreach ( $names as $name ) {
2532 + if ( false !== stripos( $needle, $name ) ) {
2533 + $names_it = true;
2534 + break;
2535 + }
2536 + }
2537 + if ( $names_it && self::target_matches( $needle, $handle, $src ) ) {
2538 + return true;
2539 + }
2540 + }
2541 + return false;
2542 + }
2543 +
2544 + /** Both toggles on: delay_js and its carry-the-inline-snippets mode. */
2545 + private static function smart_delay_enabled(): bool {
2546 + $opts = self::opts();
2547 + return ! empty( $opts['delay_js'] ) && ! empty( $opts['delay_js_smart'] );
2548 + }
2549 +
2550 + /**
2551 + * Would Smart Delay postpone this handle's tag?
2552 + *
2553 + * The snippet-parking filter runs when WordPress prints a handle's
2554 + * `before` snippet — BEFORE script_loader_tag sees the tag itself — so
2555 + * the decision cannot be read back from what happened to the tag; both
2556 + * sides evaluate this same predicate. It mirrors the handle/src checks
2557 + * of delay_script_tag() only: the tag-level outs there (an optimizer
2558 + * opt-out attribute, a non-executable type) are invisible here, so a
2559 + * tag that keeps itself eager through one of those can still have its
2560 + * snippets parked. That parks an init until first interaction rather
2561 + * than throwing, and Smart Delay is opt-in — acceptable, and documented
2562 + * on the setting.
2563 + */
2564 + private static function smart_delays_handle( string $handle ): bool {
2565 + if ( '' === $handle ) {
2566 + return false;
2567 + }
2568 + // Check the URL delay_script_tag() checks. original_src() is set
2569 + // only when Minify JS rewrote the URL, so with Minify JS off it was
2570 + // '' here. A URL exclusion then passed here and failed there, and
2571 + // the snippets were parked while the script stayed live.
2572 + $src = self::original_src( $handle );
2573 + if ( '' === $src ) {
2574 + $src = self::registered_src( $handle );
2575 + }
2576 + if ( self::is_excluded_script( $handle, $src, true ) ) {
2577 + return false;
2578 + }
2579 + return self::is_delay_target( $handle, $src );
2580 + }
2581 +
2582 + /**
2583 + * A handle's registered URL, made absolute the way WP_Scripts prints it,
2584 + * without the version query. '' when the handle has no file.
2585 + *
2586 + * @param string $handle Script handle.
2587 + */
2588 + private static function registered_src( string $handle ): string {
2589 + if ( ! function_exists( 'wp_scripts' ) ) {
2590 + return '';
2591 + }
2592 + $scripts = wp_scripts();
2593 + if ( ! $scripts instanceof \WP_Scripts ) {
2594 + return '';
2595 + }
2596 + $reg = $scripts->registered[ $handle ] ?? null;
2597 + $src = ( is_object( $reg ) && is_string( $reg->src ) ) ? $reg->src : '';
2598 + if ( '' !== $src && ! preg_match( '#^(?:https?:)?//#i', $src ) ) {
2599 + $src = (string) ( $scripts->base_url ?? '' ) . $src;
2600 + }
2601 + return $src;
2602 + }
2603 +
2604 + /**
2605 + * Filter: `script_loader_tag`, after every other xSpeed pass. Un-park a
2606 + * handle's before/after snippets when its external tag was not delayed.
2607 + *
2608 + * park_smart_inline() decides before the tag exists, so a later rule
2609 + * that keeps the tag live (an opt-out attribute, a non-executable type,
2610 + * the late opt-out revert, another plugin's filter) left the snippets
2611 + * parked and the script live. The script then ran without the config
2612 + * its `before` snippet sets, which is how Elementor's frontend lost
2613 + * elementorFrontendConfig. This filter makes that state impossible.
2614 + *
2615 + * @param string $tag
2616 + * @param string $handle
2617 + * @param string $src
2618 + */
2619 + public static function unpark_orphaned_smart_inline( $tag, $handle, $src ): string {
2620 + if ( ! is_string( $tag ) || '' === $tag || '' === (string) $handle || false === stripos( $tag, 'text/xspeed-delayed' ) ) {
2621 + return (string) $tag;
2622 + }
2623 + // Only the external tag in this string can carry data-xs-src. Its
2624 + // `src` is gone once delayed, so open_tag_offsets() cannot find it.
2625 + if ( preg_match( '#<script\b[^>]*(?<![-\w])data-xs-src\s*=#i', $tag ) ) {
2626 + return $tag;
2627 + }
2628 + return (string) preg_replace_callback(
2629 + '#<script\b([^>]*\sid\s*=\s*(["\'])' . preg_quote( (string) $handle, '#' ) . '-js-(?:before|after)\2[^>]*)>#i',
2630 + static function ( array $m ): string {
2631 + $attrs = $m[1];
2632 + if ( 'text/xspeed-delayed' !== self::extract_type( $attrs ) ) {
2633 + return $m[0];
2634 + }
2635 + $orig = preg_match( '#\sdata-xs-type\s*=\s*(["\'])([^"\']*)\1#i', $attrs, $t ) ? $t[2] : '';
2636 + $attrs = (string) preg_replace( self::TYPE_ATTR_RE, '', $attrs );
2637 + $attrs = (string) preg_replace( '#\sdata-xs-(?:delay|type)\s*=\s*(["\'])[^"\']*\1#i', '', $attrs );
2638 + if ( '' !== $orig ) {
2639 + $attrs .= ' type="' . esc_attr( $orig ) . '"';
2640 + }
2641 + return '<script' . $attrs . '>';
2642 + },
2643 + $tag
2644 + );
2645 + }
2646 +
2647 + /**
2648 + * Park a delayed handle's own before/after snippet, in Smart Delay mode.
2649 + *
2650 + * Runs on `wp_inline_script_attributes`, which fires for every inline
2651 + * script WordPress prints itself — so it works on pages the HTML buffer
2652 + * never filters (a BYPASS route like /cart), where the handle's tag is
2653 + * still delayed by script_loader_tag. `-js-extra` stays eager on
2654 + * purpose: it is data assignments, harmless early and sometimes read by
2655 + * eager code.
2656 + *
2657 + * @param mixed $attributes Inline script attributes.
2658 + * @param string $javascript The snippet body.
2659 + * @return mixed
2660 + */
2661 + public static function park_smart_inline( $attributes, $javascript = '' ) {
2662 + if ( ! is_array( $attributes ) || ! self::smart_delay_enabled() || self::skip_in_non_frontend_context() ) {
2663 + return $attributes;
2664 + }
2665 + $id = isset( $attributes['id'] ) ? (string) $attributes['id'] : '';
2666 + if ( ! preg_match( '#^(.+)-js-(?:before|after)$#', $id, $m ) ) {
2667 + return $attributes;
2668 + }
2669 + if ( ! self::smart_delays_handle( $m[1] ) ) {
2670 + return $attributes;
2671 + }
2672 + $type = isset( $attributes['type'] ) ? (string) $attributes['type'] : '';
2673 + if ( in_array( $type, self::NON_EXECUTABLE_TYPES, true ) ) {
2674 + return $attributes; // data, or parked by someone else on purpose.
2675 + }
2676 + // A delayed document.write replays after the document has closed
2677 + // and replaces the page. Same rule as delay_inline_snippets().
2678 + if ( false !== stripos( (string) $javascript, 'document.write' ) ) {
2679 + return $attributes;
2680 + }
2681 + if ( '' !== $type && ! in_array( $type, self::DEFAULT_JS_TYPES, true ) ) {
2682 + $stash = (string) preg_replace( '#[^a-z0-9/+.\-]#', '', $type );
2683 + if ( '' !== $stash ) {
2684 + $attributes['data-xs-type'] = $stash;
2685 + }
2686 + }
2687 + $attributes['type'] = 'text/xspeed-delayed';
2688 + $attributes['data-xs-delay'] = '1';
2689 + return $attributes;
2690 + }
2691 +
1757 2692 private static function is_delay_target( string $handle, string $src ): bool {
1758 2693 $opts = self::opts();
1759 2694 $targets = is_array( $opts['delay_js_targets'] ?? null ) ? $opts['delay_js_targets'] : array();
1760 2695 $targets = array_filter( array_map( 'strval', $targets ), static fn( $t ) => '' !== $t );
@@ -1891,10 +2826,13 @@
1891 2826 self::$opts = null;
1892 2827 self::$uploads_base = null;
1893 2828 self::$delay_bootstrap_printed = false;
1894 2829 self::$js_measured_layout = null;
2830 + self::$has_critical_css = null;
2831 + self::$exclusion_floor = null;
1895 2832 self::$inline_bound_handles = null;
1896 2833 self::$pristine_tag = array();
2834 + self::$our_late_attrs = array();
1897 2835 }
1898 2836
1899 2837 /**
1900 2838 * Per-request memo for inline_bound_handles(). Null = not resolved.
@@ -2046,8 +2984,41 @@
2046 2984 *
2047 2985 * @var bool|null
2048 2986 */
2049 2987 private static $js_measured_layout = null;
2988 +
2989 + /**
2990 + * Per-request memo for page_has_critical_css(). Null = not resolved.
2991 + *
2992 + * @var bool|null
2993 + */
2994 + private static $has_critical_css = null;
2995 +
2996 + /**
2997 + * Does something inline critical CSS for the page being served?
2998 + *
2999 + * Free generates none, so the answer comes from the filter: an extension
3000 + * that inlines critical CSS for this page returns true, and a site whose
3001 + * theme ships its own can too. Resolved once per request, because every
3002 + * stylesheet tag asks.
3003 + */
3004 + public static function page_has_critical_css(): bool {
3005 + if ( null === self::$has_critical_css ) {
3006 + /**
3007 + * Whether the page being served has critical CSS inlined in its head.
3008 + *
3009 + * Async CSS defers stylesheets only when this is true; without
3010 + * critical CSS it leaves them render-blocking, because deferring
3011 + * them makes the page paint unstyled and shift. Return true when
3012 + * something inlines critical CSS for this page, or to keep deferring
3013 + * without it.
3014 + *
3015 + * @param bool $has_critical_css Default false.
3016 + */
3017 + self::$has_critical_css = (bool) apply_filters( 'xspeed_async_css_page_has_critical_css', false );
3018 + }
3019 + return self::$has_critical_css;
3020 + }
2050 3021
2051 3022 /**
2052 3023 * Scripts that lay out the page by measuring the DOM.
2053 3024 *