PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.7
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.7
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 1.1.2 1.1.3 1.1.4 All 33 releases
← All changes | includes/class-minify-filters.php +426 -100 1.3.5 → 1.3.7 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.
@@ -548,9 +558,15 @@
548 558 // dependent that touches a global its dependency defines. (#234)
549 559 //
550 560 // The lookahead scans only within the tag (`[^>]*`) for ` src=`, so
551 561 // an inline `<script id="…-js-before">` can never match.
552 - 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;
553 569 }
554 570
555 571 /**
556 572 * Filter: `script_loader_tag` — rewrite src= to data-xs-src= so the
@@ -592,9 +608,16 @@
592 608 // the moment jquery-core is delayed. A handle the user NAMED in
593 609 // delay_js_targets is still delayed — an explicit entry is the user
594 610 // saying they know the inline consumer is safe to break or absent.
595 611 if ( isset( self::inline_bound_handles()[ (string) $handle ] )
596 - && ! 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() ) {
597 620 return $tag;
598 621 }
599 622 // A non-executable type means this tag is data, or is being held by
600 623 // somebody else on purpose. The buffer pass has always checked this;
@@ -637,9 +660,9 @@
637 660 // would win over a marker appended behind it and keep executing.
638 661 // A non-default original type is stashed in data-xs-type so the
639 662 // bootstrap can restore it on replay (#274 — type is what a script
640 663 // IS; a parked `type="module"` must come back as a module).
641 - $tag = (string) preg_replace_callback(
664 + $parked = (string) preg_replace_callback(
642 665 '#<script\b([^>]*)>#i',
643 666 static function ( array $m ): string {
644 667 return '<script' . self::park_type_attrs( $m[1] ) . '>';
645 668 },
@@ -645,9 +668,14 @@
645 668 },
646 669 $tag,
647 670 1
648 671 );
649 - 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;
650 678 }
651 679
652 680 /**
653 681 * Script types the buffer pass must never touch. `<script>` carries
@@ -1029,11 +1057,13 @@
1029 1057 if ( empty( $opts['delay_js'] ) ) {
1030 1058 return $html;
1031 1059 }
1032 1060
1061 + $handle_delayed = self::handle_delay_outcomes( $html );
1062 +
1033 1063 $out = preg_replace_callback(
1034 1064 '#<script\b([^>]*)>(.*?)</script>#is',
1035 - static function ( array $m ): string {
1065 + static function ( array $m ) use ( $handle_delayed ): string {
1036 1066 list( $whole, $attrs, $body ) = $m;
1037 1067
1038 1068 if ( '' === trim( $body ) ) {
1039 1069 return $whole;
@@ -1081,8 +1111,38 @@
1081 1111 if ( preg_match( '#(?<![-\w])id\s*=\s*(["\'])xspeed-#i', $attrs ) ) {
1082 1112 return $whole;
1083 1113 }
1084 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 +
1085 1145 // The body stands in for the URL in the lists the src passes
1086 1146 // consult — but NOT via is_delay_target(), whose empty-list
1087 1147 // default is "delay everything". That default is right for a
1088 1148 // tag with a URL and catastrophic here: it would park every
@@ -1088,12 +1148,16 @@
1088 1148 // tag with a URL and catastrophic here: it would park every
1089 1149 // inline script on the page. Inline code is delayed only on a
1090 1150 // positive identification — the body names a known vendor
1091 1151 // host, or a fragment the user targeted — and the exclusion
1092 - // list still wins first.
1093 - 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 ) ) {
1094 1157 return $whole;
1095 1158 }
1159 +
1096 1160 if ( ! self::matches_known_third_party( $body ) && ! self::matches_user_targets( $body ) ) {
1097 1161 return $whole;
1098 1162 }
1099 1163
@@ -1112,8 +1176,33 @@
1112 1176 return null === $out ? $html : $out;
1113 1177 }
1114 1178
1115 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 + /**
1116 1205 * Inline bootstrap that flips delayed scripts on the first user
1117 1206 * interaction. Printed once on wp_footer priority 1000.
1118 1207 */
1119 1208 public static function print_delay_bootstrap(): void {
@@ -1133,70 +1222,49 @@
1133 1222 $opts = self::opts();
1134 1223 $timeout = isset( $opts['delay_js_timeout'] ) ? (int) $opts['delay_js_timeout'] : 8000;
1135 1224 $timeout = max( 0, min( 60000, $timeout ) );
1136 1225
1137 - // Tiny vanilla bootstrap; keep it self-contained so the page
1138 - // has no JS dependencies before the first interaction.
1139 - ?>
1140 -<script id="xspeed-delay-bootstrap">
1141 -(function(){
1142 - var events=['mousemove','keydown','touchstart','scroll','wheel'];
1143 - var fired=false;
1144 - function load(){
1145 - if(fired)return;fired=true;
1146 - events.forEach(function(e){window.removeEventListener(e,load,{passive:true,capture:true});});
1147 - var delayed=document.querySelectorAll('script[data-xs-delay]');
1148 - delayed.forEach(function(s){
1149 - var n=document.createElement('script');
1150 - // A dynamically-created script is async by default, so replayed
1151 - // EXTERNALS would race each other; async=false restores document
1152 - // order among the externals. Narrower guarantee, stated plainly:
1153 - // a replayed INLINE script still executes synchronously at its
1154 - // replaceChild, i.e. possibly before an earlier external has
1155 - // finished LOADING — so an inline consumer of a delayed external
1156 - // is only safe when both were delayed by explicit user targeting
1157 - // (the inline-bound guard keeps the implicit case eager).
1158 - n.async=false;
1159 - // Nonce hiding: a connected element's nonce CONTENT attribute reads
1160 - // as "", so copying it via the attribute loop would hand the clone
1161 - // an empty nonce and a nonce-based CSP would block the replay. The
1162 - // IDL property still carries the real value.
1163 - if(s.nonce){n.nonce=s.nonce;}
1164 - Array.prototype.slice.call(s.attributes).forEach(function(a){
1165 - if(a.name==='data-xs-src'){n.setAttribute('src',a.value);return;}
1166 - if(a.name==='data-xs-delay')return;
1167 - if(a.name==='nonce')return;
1168 - // A parked inline tag's ORIGINAL type (module, mostly) rides in
1169 - // data-xs-type — restore it, or the replay runs a module as a
1170 - // classic script and its imports throw. (#274)
1171 - if(a.name==='data-xs-type'){n.setAttribute('type',a.value);return;}
1172 - // `type` is what a script IS, not decoration, so it is carried over
1173 - // — with ONE exception: our own inline parking marker, which exists
1174 - // only to stop the browser executing the original and must not be
1175 - // copied onto the replacement. Dropping type wholesale broke two
1176 - // things: `type="module"` became a classic script (core's Script
1177 - // Modules — Navigation, lightbox, Query Loop — threw "Cannot use
1178 - // import statement outside a module" on the default theme), and
1179 - // `type="text/plain"`, which is precisely how a consent manager
1180 - // parks a blocked third-party script, became executable again. The
1181 - // second is a privacy failure, not a broken feature. (#274)
1182 - if(a.name==='type'&&a.value==='text/xspeed-delayed')return;
1183 - n.setAttribute(a.name,a.value);
1184 - });
1185 - if(!s.hasAttribute('data-xs-src')){n.text=s.text;}
1186 - s.parentNode.replaceChild(n,s);
1187 - });
1188 - }
1189 - events.forEach(function(e){window.addEventListener(e,load,{passive:true,capture:true});});
1190 -<?php if ( $timeout > 0 ) : ?>
1191 - setTimeout(load,<?php echo (int) $timeout; ?>);
1192 -<?php endif; ?>
1193 -})();
1194 -</script>
1195 - <?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' ) );
1196 1237 }
1197 1238
1239 + /** The delay bootstrap's code, read once per request. */
1240 + private static $delay_bootstrap_js = null;
1241 +
1198 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 + /**
1199 1267 * Filter: `style_loader_tag` — wrap stylesheets in the
1200 1268 * print → onload="all" pattern so they download non-blocking.
1201 1269 * Pairs with critical CSS workflows. Adds a <noscript> fallback so
1202 1270 * users with JS disabled still get styles applied (via media="all").
@@ -1216,8 +1284,21 @@
1216 1284 // want to fight with explicit author intent.
1217 1285 if ( false === stripos( $tag, 'rel=\'stylesheet\'' ) && false === stripos( $tag, 'rel="stylesheet"' ) ) {
1218 1286 return $tag;
1219 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 + }
1220 1301 // The stylesheets that lay the page out stay render-blocking.
1221 1302 //
1222 1303 // This transform moves a sheet to AFTER first paint. That is the
1223 1304 // point of it — but a sheet the layout depends on is then missing
@@ -1524,12 +1605,19 @@
1524 1605 * than a hard-coded list.
1525 1606 * - WordPress' own BLOCK and layout sheets (`wp-block-library`,
1526 1607 * `global-styles`, `classic-theme-styles`). These style block
1527 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.
1528 1615 *
1529 - * Everything else — plugin sheets, icon fonts, widget and page-builder
1530 - * add-ons, the long tail that makes async CSS worth having — is still
1531 - * 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.
1532 1620 *
1533 1621 * A site WITH critical CSS can defer these too; that is what the
1534 1622 * `xspeed_async_css_layout_critical` filter is for.
1535 1623 *
@@ -1546,19 +1634,21 @@
1546 1634 'wp-block-library-theme',
1547 1635 'global-styles',
1548 1636 'classic-theme-styles',
1549 1637 );
1550 - $critical = in_array( $handle, $core, true );
1638 + $critical = in_array( $handle, $core, true ) || self::is_builder_grid_style( $handle );
1551 1639
1552 1640 // The active theme's own sheets.
1553 1641 //
1554 1642 // Matched on the theme stem, but NOT as a bare prefix: a plugin from
1555 1643 // the same vendor shares it (the Kadence theme is `kadence`, while
1556 - // `kadence-blocks-rowlayout` and `kadence-fonts-gfonts` come from the
1557 - // Kadence Blocks PLUGIN and a webfont loader). Treating those as
1558 - // layout-critical would leave almost nothing deferred and quietly
1559 - // undo the feature. So the stem must be followed by a recognised
1560 - // 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.
1561 1651 if ( ! $critical && function_exists( 'get_template' ) ) {
1562 1652 $areas = array(
1563 1653 'style',
1564 1654 'global',
@@ -1603,8 +1693,28 @@
1603 1693 return (bool) apply_filters( 'xspeed_async_css_layout_critical', $critical, $handle );
1604 1694 }
1605 1695
1606 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 + /**
1607 1717 * Filter: `style_loader_src` + `script_loader_src` — strip the
1608 1718 * ?ver=X.Y query string that WP appends for cache busting. Some
1609 1719 * CDNs / reverse proxies cache better when the URL has no query.
1610 1720 *
@@ -1807,11 +1917,11 @@
1807 1917 );
1808 1918
1809 1919 /**
1810 1920 * Consent managers are never deferred, and never delayed by a broad
1811 - * setting — only an EXPLICIT delay_js_targets entry naming one lifts
1812 - * the floor (see is_excluded_script()); the `xspeed_js_exclusion_floor`
1813 - * filter remains the code-level override.
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.
1814 1924 *
1815 1925 * A consent banner is drawn by JavaScript, and it is the one thing on
1816 1926 * the page that has to appear before anything else happens. Delay it
1817 1927 * and a visitor who lands, reads and leaves without touching the page
@@ -1893,8 +2003,62 @@
1893 2003 'surecookie',
1894 2004 );
1895 2005
1896 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 + /**
1897 2061 * Per-request memo for exclusion_floor(). Null = not resolved.
1898 2062 *
1899 2063 * @var string[]|null
1900 2064 */
@@ -1928,11 +2092,12 @@
1928 2092 /**
1929 2093 * @param string $handle Script handle ('' on the buffer sweep
1930 2094 * when no id survived).
1931 2095 * @param string $src Script URL.
1932 - * @param bool $named_lifts_floor Delay paths only: a handle/URL the user
1933 - * EXPLICITLY typed into delay_js_targets
1934 - * passes the consent floor. Typing a
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
1935 2100 * consent manager's name into an
1936 2101 * allow-list is the site owner taking the
1937 2102 * consent-timing decision back — GDPR is
1938 2103 * theirs to weigh, not ours; the floor
@@ -1964,10 +2129,13 @@
1964 2129 // one that cleared the textarea has no list at all. Neither may
1965 2130 // hide the banner. (#275)
1966 2131 foreach ( self::exclusion_floor() as $needle ) {
1967 2132 if ( self::target_matches( $needle, $handle, $src ) ) {
1968 - if ( $named_lifts_floor && self::is_user_named_target( $handle, $src ) ) {
1969 - break;
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;
1970 2138 }
1971 2139 return true;
1972 2140 }
1973 2141 }
@@ -2038,8 +2206,131 @@
2038 2206 }
2039 2207 return false;
2040 2208 }
2041 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 +
2042 2333 private static function is_delay_target( string $handle, string $src ): bool {
2043 2334 $opts = self::opts();
2044 2335 $targets = is_array( $opts['delay_js_targets'] ?? null ) ? $opts['delay_js_targets'] : array();
2045 2336 $targets = array_filter( array_map( 'strval', $targets ), static fn( $t ) => '' !== $t );
@@ -2176,11 +2467,13 @@
2176 2467 self::$opts = null;
2177 2468 self::$uploads_base = null;
2178 2469 self::$delay_bootstrap_printed = false;
2179 2470 self::$js_measured_layout = null;
2471 + self::$has_critical_css = null;
2180 2472 self::$exclusion_floor = null;
2181 2473 self::$inline_bound_handles = null;
2182 2474 self::$pristine_tag = array();
2475 + self::$our_late_attrs = array();
2183 2476 }
2184 2477
2185 2478 /**
2186 2479 * Per-request memo for inline_bound_handles(). Null = not resolved.
@@ -2332,8 +2625,41 @@
2332 2625 *
2333 2626 * @var bool|null
2334 2627 */
2335 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 + }
2336 2662
2337 2663 /**
2338 2664 * Scripts that lay out the page by measuring the DOM.
2339 2665 *