PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.4
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.4
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 1.1.5 1.1.6 1.1.7 All 30 releases
← All changes | includes/class-asset-combiner.php +439 -29 1.1.71.3.4 View file →
@@ -133,10 +133,33 @@
133 133 continue;
134 134 }
135 135 $body = self::resolve_imports( $body, $info['url'], 0 );
136 136 $body = self::rewrite_url_paths( $body, $info['url'] );
137 - $contents .= "/* xspeed: $handle */\n" . $body . "\n";
137 + // No per-handle banner comment: it is a debugging aid with no
138 + // runtime value, and the minifier below preserves a comment
139 + // that opens a chunk, so each one survived as a `/* xspeed */`
140 + // stub that Lighthouse still counts as removable bytes.
141 + // The handle list lives in the cache key, not in the payload.
142 + $contents .= $body . "\n";
138 143 }
144 +
145 + // Minify the JOIN, not just the parts (issue #331).
146 + //
147 + // Every input arrives here already minified, but the join itself
148 + // is not: a `/* xspeed: <handle> */` banner per part, a newline
149 + // after each, and whatever non-bang comments the sources kept.
150 + // Nothing downstream removes them — Minifier::rewrite_style()
151 + // deliberately skips anything under /cache/xspeed/ (re-minifying
152 + // our own output produced a second hash whose URL 404'd after a
153 + // purge), so this file was the end of the line and shipped as-is.
154 + //
155 + // The visible cost was small (~2 KB) but the scoring cost was not:
156 + // Lighthouse's `unminified-css` is near-binary, so one failing
157 + // file drops the audit to 0.5 — and the only offender on the page
158 + // was the artifact we generated, which then docked the site on
159 + // xSpeed Scan's own A2 check while the UI reported minify as on.
160 + $contents = self::minify_css_body( $contents );
161 +
139 162 // Atomic write: file_put_contents with LOCK_EX so concurrent
140 163 // renders don't race.
141 164 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_put_contents_file_put_contents -- WP_Filesystem requires admin context, unavailable on frontend.
142 165 file_put_contents( $out_file, $contents, LOCK_EX );
@@ -216,12 +239,68 @@
216 239 if ( count( $bucket ) < 2 ) {
217 240 return;
218 241 }
219 242
243 + // Split by print group — head (0) and footer (1) get their own bundle.
244 + //
245 + // Carrying everything on ONE carrier meant the whole bucket inherited
246 + // that handle's placement, and the first handle in dependency order is
247 + // almost always jquery-core, which WordPress registers with no group
248 + // data at all — i.e. the HEAD. Every footer script absorbed alongside
249 + // it was therefore hoisted into the head and executed as one
250 + // synchronous blob before first paint: correctness-safer than the old
251 + // forced footer, but render-blocking, and the exact inverse of what a
252 + // speed plugin should ship. Bucketing by group is the same move
253 + // combine_styles() already makes for media types. (#289, PR #290 review)
254 + foreach ( self::split_by_group( $wp_scripts, $bucket ) as $group => $group_bucket ) {
255 + if ( count( $group_bucket ) < 2 ) {
256 + continue; // nothing to gain from combining a single file.
257 + }
258 + self::combine_script_group( $wp_scripts, (int) $group, $group_bucket );
259 + }
260 + }
261 +
262 + /**
263 + * Partition a bucket into WordPress's print groups: 0 = head, 1 = footer.
264 + *
265 + * Reads $wp_scripts->groups, NOT the declared `extra['group']`, because
266 + * the declared value is not authoritative: WordPress promotes a
267 + * footer-registered dependency of a head script into the head. all_deps()
268 + * populates the effective values and prints nothing, so resolving them
269 + * here keeps our split consistent with what WordPress would have done on
270 + * its own. (PR #290 review)
271 + *
272 + * @param array<string,array<mixed>> $bucket handle => info map.
273 + * @return array<int,array<string,array<mixed>>> group => bucket.
274 + */
275 + private static function split_by_group( \WP_Scripts $wp_scripts, array $bucket ): array {
276 + // Resolve effective groups for everything queued. Safe to call at
277 + // wp_enqueue_scripts: it walks dependencies and fills ->groups
278 + // without emitting a single tag.
279 + $wp_scripts->all_deps( $wp_scripts->queue, false );
280 +
281 + $groups = array();
282 + foreach ( $bucket as $handle => $info ) {
283 + $group = isset( $wp_scripts->groups[ $handle ] ) ? (int) $wp_scripts->groups[ $handle ] : 0;
284 + $groups[ $group ][ $handle ] = $info;
285 + }
286 +
287 + return $groups;
288 + }
289 +
290 + /**
291 + * Build and attach one combined file for a single print group.
292 + *
293 + * @param int $group 0 = head, 1 = footer.
294 + * @param array<string,array<mixed>> $bucket handle => info map for this group.
295 + */
296 + private static function combine_script_group( \WP_Scripts $wp_scripts, int $group, array $bucket ): void {
220 297 $key = self::cache_key( $bucket );
221 298 $dir = self::cache_dir();
222 - $out_file = $dir . '/combined-' . $key . '.js';
223 - $out_url = self::cache_url() . '/combined-' . $key . '.js';
299 + // Group in the filename so a head and a footer bundle can never
300 + // collide on one cache key.
301 + $out_file = $dir . '/combined-g' . $group . '-' . $key . '.js';
302 + $out_url = self::cache_url() . '/combined-g' . $group . '-' . $key . '.js';
224 303
225 304 if ( ! file_exists( $out_file ) ) {
226 305 self::ensure_dir( $dir );
227 306 $contents = '';
@@ -237,17 +316,187 @@
237 316 } else {
238 317 self::mark_in_use( $out_file );
239 318 }
240 319
320 + self::attach_to_carrier( $wp_scripts, $bucket, $out_url, $key );
321 + }
322 +
323 + /**
324 + * carrier handle => the handles whose src it now serves.
325 + *
326 + * @var array<string,string[]>
327 + */
328 + private static $carriers = array();
329 +
330 + /** Whether the print-time sweep is hooked. */
331 + private static $late_sweep_hooked = false;
332 +
333 + /** Payload fingerprints already re-homed, so a second sweep is a no-op. */
334 + private static $rehomed = array();
335 +
336 + /**
337 + * Point the combined file at the FIRST not-yet-printed bucket handle and
338 + * blank the rest, instead of dequeuing everything and appending a fresh
339 + * handle.
340 + *
341 + * The old approach registered `xspeed-combined-js` with `array()` deps and
342 + * a hard-coded `$in_footer = true`, then dequeued the originals. Three
343 + * things went wrong with that:
344 + *
345 + * 1. No dependency edges. The bundle declared no relationship to the
346 + * handles that stayed in the queue (external, async/deferred,
347 + * localized), so WordPress was free to print it in any order relative
348 + * to them.
349 + * 2. Forced to the footer. Every head script in the bucket was relocated
350 + * behind any inline <script> in the head or body that expected it.
351 + * 3. dequeue() leaves a handle REGISTERED and re-enqueueable, so anything
352 + * enqueuing it later printed it a second time — while its code was
353 + * already inside the bundle.
354 + *
355 + * Together those produce the reported break: `jquery-core` gets absorbed
356 + * into a footer bundle, something still prints `jquery.min.js` in the
357 + * head, and the second jQuery replaces the first — discarding every plugin
358 + * the bundle had attached to it. `jQuery.fn.waypoint` becomes undefined
359 + * even though the library loaded, and Elementor's module layer initialises
360 + * twice. Measured on a fixture of that stack: five handles present both
361 + * inside the bundle and as their own tag. (#289)
362 + *
363 + * Carrying the file on an existing handle fixes all three at once — the
364 + * merged script keeps that handle's queue position, its dependency edges
365 + * and its head/footer placement, and nothing is dequeued so nothing can be
366 + * re-enqueued behind our back. This is what combine_styles() has always
367 + * done; the JS path never got it.
368 + *
369 + * @param array<string,array<mixed>> $bucket handle => info map, in dependency order.
370 + * @param string $out_url URL of the combined file.
371 + * @param string $key Cache key, used as the version.
372 + */
373 + private static function attach_to_carrier( \WP_Scripts $wp_scripts, array $bucket, string $out_url, string $key ): void {
374 + $done = (array) $wp_scripts->done;
375 + $carrier_set = false;
376 + $carrier = '';
377 + $absorbed = array();
378 +
241 379 foreach ( $bucket as $handle => $info ) {
242 - $wp_scripts->dequeue( $handle );
380 + $reg = $wp_scripts->registered[ $handle ] ?? null;
381 + if ( ! $reg instanceof \_WP_Dependency ) {
382 + continue;
383 + }
384 +
385 + if ( ! $carrier_set && ! in_array( $handle, $done, true ) ) {
386 + // Carry the bundle on this handle's slot. Its deps, its queue
387 + // position and its in_footer flag all stay exactly as the
388 + // enqueuing plugin set them.
389 + $reg->src = $out_url;
390 + $reg->ver = $key;
391 + $carrier = $handle;
392 + $carrier_set = true;
393 + continue;
394 + }
395 +
396 + // Every other absorbed handle keeps its registration and its queue
397 + // membership — only the src is blanked, so no second <script src>
398 + // is emitted while any wp_add_inline_script() / wp_localize_script()
399 + // data attached to it still prints. Dequeuing instead would drop
400 + // that data on the floor and leave the handle re-enqueueable.
401 + $reg->src = false;
402 + $reg->ver = null;
403 + $absorbed[] = $handle;
243 404 }
244 - $combined_handle = 'xspeed-combined-js';
245 - wp_register_script( $combined_handle, $out_url, array(), $key, true );
246 - wp_enqueue_script( $combined_handle );
405 +
406 + // No carrier means every handle in this bucket had ALREADY printed —
407 + // so its code has already executed in the browser.
408 + //
409 + // Emitting the bundle anyway would re-run all of it, including a
410 + // second jQuery: precisely the double-execution this method exists to
411 + // prevent, and deterministic rather than occasional. The CSS path can
412 + // afford its equivalent fallback because a duplicate stylesheet is
413 + // merely redundant; a duplicate script re-initialises everything.
414 + //
415 + // So we do nothing: the page keeps the individual files it already
416 + // printed — no combining benefit for this bucket, but correct.
417 + // (PR #290 review)
418 + if ( ! $carrier_set ) {
419 + return;
420 + }
421 +
422 + // Remember what this carrier swallowed, so a payload attached to an
423 + // absorbed handle AFTER we ran can still be re-homed onto the bundle
424 + // at print time. See sweep_late_inline() for why that is needed.
425 + self::$carriers[ $carrier ] = $absorbed;
426 +
427 + if ( ! self::$late_sweep_hooked ) {
428 + self::$late_sweep_hooked = true;
429 + // Priority 0 on both print hooks: ahead of WP emitting the queue,
430 + // and ahead of Defer_Js rewriting the tags it is about to print.
431 + add_action( 'wp_print_scripts', array( __CLASS__, 'sweep_late_inline' ), 0 );
432 + add_action( 'wp_print_footer_scripts', array( __CLASS__, 'sweep_late_inline' ), 0 );
433 + }
247 434 }
248 435
249 436 /**
437 + * Re-home inline payloads that arrived after the bundle was built.
438 + *
439 + * combine_scripts() runs on wp_enqueue_scripts, and combinable_script_info()
440 + * refuses any handle that ALREADY carries inline data — so at that moment a
441 + * page builder has attached nothing. Elementor adds elementorFrontendConfig
442 + * from Frontend::wp_footer(), thousands of hook-ticks later, onto a handle
443 + * whose src we have since blanked.
444 + *
445 + * That payload is not lost: blanking `src` (rather than dequeuing) leaves
446 + * the handle registered, so WordPress still prints it. But it prints at the
447 + * ABSORBED handle's queue position, which is behind the carrier — and a
448 + * `before` payload exists precisely to run ahead of the code that reads it.
449 + * The config therefore landed after the bundle that consumes it, and the
450 + * script initialised against an undefined global.
451 + *
452 + * Moving a late `before` payload onto the carrier restores that contract.
453 + * `after` payloads are left alone: their position behind the code is
454 + * already correct wherever they print.
455 + *
456 + * Idempotent by fingerprint, so running on both print hooks is safe. (#246)
457 + */
458 + public static function sweep_late_inline(): void {
459 + global $wp_scripts;
460 + if ( ! $wp_scripts instanceof \WP_Scripts || empty( self::$carriers ) ) {
461 + return;
462 + }
463 +
464 + foreach ( self::$carriers as $carrier => $absorbed ) {
465 + if ( ! isset( $wp_scripts->registered[ $carrier ] ) ) {
466 + continue;
467 + }
468 + foreach ( $absorbed as $handle ) {
469 + $reg = $wp_scripts->registered[ $handle ] ?? null;
470 + if ( ! $reg instanceof \_WP_Dependency || empty( $reg->extra['before'] ) ) {
471 + continue;
472 + }
473 + if ( ! is_array( $reg->extra['before'] ) ) {
474 + continue;
475 + }
476 +
477 + foreach ( $reg->extra['before'] as $payload ) {
478 + // WP seeds `before` with a leading empty string; skip it
479 + // rather than emitting a blank <script>.
480 + if ( ! is_string( $payload ) || '' === trim( $payload ) ) {
481 + continue;
482 + }
483 + $fingerprint = md5( $payload );
484 + if ( isset( self::$rehomed[ $fingerprint ] ) ) {
485 + continue;
486 + }
487 + self::$rehomed[ $fingerprint ] = true;
488 + wp_add_inline_script( $carrier, $payload, 'before' );
489 + }
490 +
491 + // Clear the source so the payload is not ALSO printed at the
492 + // absorbed handle's own position, after the bundle.
493 + unset( $reg->extra['before'] );
494 + }
495 + }
496 + }
497 +
498 + /**
250 499 * Walk WP_Styles->queue, return the handles whose src is a local file we
251 500 * can safely combine, grouped BY media type so each media gets its own
252 501 * combined file. Shape:
253 502 * [ media => [ handle => [ 'url' => …, 'path' => …, 'mtime' => int, 'src' => … ] ] ].
@@ -299,36 +548,160 @@
299 548 return $groups;
300 549 }
301 550
302 551 private static function collect_local_script_handles( \WP_Scripts $wp_scripts ): array {
552 + // `queue` holds only what was explicitly enqueued — never the
553 + // dependencies WP resolves at print time. Walking it alone combined
554 + // `admin-bar` while silently dropping its `hoverintent-js` dep, so the
555 + // bundle called a function that was never in it:
556 + // "hoverintent is not a function", and every admin-bar hover menu died
557 + // for logged-in visitors. Expand deps first, then emit in dependency
558 + // order. (#204)
559 + $expanded = self::expand_with_deps( $wp_scripts );
560 +
303 561 $out = array();
304 - foreach ( $wp_scripts->queue as $handle ) {
305 - if ( ! isset( $wp_scripts->registered[ $handle ] ) ) {
562 + foreach ( $expanded as $handle ) {
563 + $info = self::combinable_script_info( $wp_scripts, $handle );
564 + if ( null === $info ) {
306 565 continue;
307 566 }
308 - $reg = $wp_scripts->registered[ $handle ];
309 - $src = (string) ( $reg->src ?? '' );
310 - if ( '' === $src ) {
311 - continue;
567 + $out[ $handle ] = $info;
568 + }
569 +
570 + // A script whose dependency could NOT be combined (inline data,
571 + // async/defer, external CDN) has to stay in the queue itself —
572 + // otherwise combining it drops the same dependency a second way.
573 + return self::drop_dependents_of_missing( $wp_scripts, $out );
574 + }
575 +
576 + /**
577 + * The queue plus every registered dependency it pulls in, in dependency
578 + * order (a handle always follows everything it depends on).
579 + *
580 + * Depth-first post-order over `WP_Scripts::$registered[$handle]->deps`.
581 + * `$seen` guards a malformed cyclic registration — a cycle can't be
582 + * ordered, so the handle is emitted once and the walk unwinds rather than
583 + * recursing forever. (#204)
584 + *
585 + * @param \WP_Scripts $wp_scripts Script registry.
586 + * @return string[] Handles, dependencies first.
587 + */
588 + private static function expand_with_deps( \WP_Scripts $wp_scripts ): array {
589 + $ordered = array();
590 + $state = array(); // handle => 1 visiting, 2 done.
591 +
592 + $visit = static function ( string $handle ) use ( &$visit, &$ordered, &$state, $wp_scripts ): void {
593 + if ( isset( $state[ $handle ] ) ) {
594 + return; // already emitted, or we're inside a cycle.
312 595 }
313 - // Skip scripts that carry inline-after data (they expect
314 - // to run at their original spot).
315 - if ( ! empty( $reg->extra['after'] ) || ! empty( $reg->extra['before'] ) || ! empty( $reg->extra['data'] ) ) {
316 - continue;
596 + $state[ $handle ] = 1;
597 + if ( isset( $wp_scripts->registered[ $handle ] ) ) {
598 + foreach ( (array) $wp_scripts->registered[ $handle ]->deps as $dep ) {
599 + $visit( (string) $dep );
600 + }
317 601 }
318 - // Skip async / defer-via-strategy.
319 - $strategy = $reg->extra['strategy'] ?? '';
320 - if ( 'async' === $strategy || 'defer' === $strategy ) {
321 - continue;
602 + $state[ $handle ] = 2;
603 + $ordered[] = $handle;
604 + };
605 +
606 + foreach ( $wp_scripts->queue as $handle ) {
607 + $visit( (string) $handle );
608 + }
609 +
610 + return $ordered;
611 + }
612 +
613 + /**
614 + * Info for a handle that can safely go in the combined bundle, or null
615 + * when it must be left in the queue.
616 + *
617 + * @param \WP_Scripts $wp_scripts Script registry.
618 + * @param string $handle Script handle.
619 + * @return array<string,mixed>|null
620 + */
621 + private static function combinable_script_info( \WP_Scripts $wp_scripts, string $handle ): ?array {
622 + if ( ! isset( $wp_scripts->registered[ $handle ] ) ) {
623 + return null;
624 + }
625 + $reg = $wp_scripts->registered[ $handle ];
626 + $src = (string) ( $reg->src ?? '' );
627 + if ( '' === $src ) {
628 + // A dependency-only alias (e.g. `jquery`) carries no file of its
629 + // own; nothing to concatenate, and its own deps were already
630 + // walked, so it isn't a blocker.
631 + return null;
632 + }
633 + // Skip scripts that carry inline-after data (they expect
634 + // to run at their original spot).
635 + if ( ! empty( $reg->extra['after'] ) || ! empty( $reg->extra['before'] ) || ! empty( $reg->extra['data'] ) ) {
636 + return null;
637 + }
638 + // A handle the user protected from defer/delay, or one Defer JS
639 + // auto-protects because inline code reads it, must not be absorbed
640 + // either. Combining moves the code into a bundle printed under a
641 + // DIFFERENT handle, so the exclusion the user wrote — matched by
642 + // handle or URL — stops matching anything and the protection is
643 + // silently gone. jquery-core is the case that bites: the check above
644 + // only catches a handle carrying its OWN inline data, while a
645 + // dependency of an inline consumer carries none, so it lands in the
646 + // bundle and the exclusion list reads as if it were still honoured.
647 + if ( \XSpeed\Minify_Filters::is_protected_from_bundling( $handle, $src ) ) {
648 + return null;
649 + }
650 + // Skip async / defer-via-strategy.
651 + $strategy = $reg->extra['strategy'] ?? '';
652 + if ( 'async' === $strategy || 'defer' === $strategy ) {
653 + return null;
654 + }
655 + $abs = self::to_absolute_url( $src );
656 + $info = self::local_info( $abs );
657 + if ( null === $info ) {
658 + return null;
659 + }
660 + return $info + array( 'src' => $src );
661 + }
662 +
663 + /**
664 + * Remove any handle whose dependency isn't in the bucket, transitively.
665 + *
666 + * Combining a script but not its dependency is exactly the #204 failure:
667 + * the bundle runs code whose prerequisite never loaded. When a dep can't
668 + * be combined — it carries inline data, is async/defer, or lives on a CDN
669 + * — the safe move is to leave the dependent in the queue too, where WP
670 + * prints both in the right order.
671 + *
672 + * A handle with no `src` (a pure alias like `jquery`) is not a blocker:
673 + * it contributes no code, and its own deps were expanded separately.
674 + *
675 + * @param \WP_Scripts $wp_scripts Script registry.
676 + * @param array<string,mixed> $bucket handle => info, dependency-ordered.
677 + * @return array<string,mixed> Filtered bucket, order preserved.
678 + */
679 + private static function drop_dependents_of_missing( \WP_Scripts $wp_scripts, array $bucket ): array {
680 + // Iterate to a fixed point: dropping A can orphan B that depends on A.
681 + do {
682 + $dropped = false;
683 + foreach ( $bucket as $handle => $info ) {
684 + if ( ! isset( $wp_scripts->registered[ $handle ] ) ) {
685 + continue;
686 + }
687 + foreach ( (array) $wp_scripts->registered[ $handle ]->deps as $dep ) {
688 + $dep = (string) $dep;
689 + if ( isset( $bucket[ $dep ] ) ) {
690 + continue; // dep is coming along.
691 + }
692 + $dep_reg = $wp_scripts->registered[ $dep ] ?? null;
693 + if ( $dep_reg && '' === (string) ( $dep_reg->src ?? '' ) ) {
694 + continue; // alias handle, contributes no code.
695 + }
696 + unset( $bucket[ $handle ] );
697 + $dropped = true;
698 + break;
699 + }
322 700 }
323 - $abs = self::to_absolute_url( $src );
324 - $info = self::local_info( $abs );
325 - if ( null === $info ) {
326 - continue;
327 - }
328 - $out[ $handle ] = $info + array( 'src' => $src );
329 - }
330 - return $out;
701 + } while ( $dropped );
702 +
703 + return $bucket;
331 704 }
332 705
333 706 /**
334 707 * Convert a possibly-relative `src` into an absolute URL.
@@ -380,8 +753,45 @@
380 753 'url' => $url,
381 754 'path' => $path,
382 755 'mtime' => (int) filemtime( $path ),
383 756 );
757 + }
758 +
759 + /**
760 + * Minify a concatenated CSS body in memory (issue #331).
761 + *
762 + * In memory on purpose: the parts have already had their `url(...)`
763 + * references rewritten by rewrite_url_paths() against each source's own
764 + * location, so handing the text to the file-based minifier — which
765 + * rebases relative URLs against the target path — would rewrite them a
766 + * second time and break every font and background image in the bundle.
767 + *
768 + * Fails open. A minifier exception, or output that came back empty or
769 + * implausibly short, returns the original text: shipping a slightly
770 + * larger stylesheet is a rounding error, shipping a truncated one
771 + * unstyles the site. Same reasoning as Minifier::minify_file()'s own
772 + * guard against mid-template-literal truncation.
773 + */
774 + public static function minify_css_body( string $css ): string {
775 + if ( '' === trim( $css ) || ! class_exists( '\\MatthiasMullie\\Minify\\CSS' ) ) {
776 + return $css;
777 + }
778 +
779 + try {
780 + $minifier = new \MatthiasMullie\Minify\CSS();
781 + $minifier->add( $css );
782 + $out = (string) $minifier->minify();
783 + } catch ( \Throwable $e ) {
784 + return $css;
785 + }
786 +
787 + // A minifier that returns nothing, or that claims a >95% saving on
788 + // already-minified inputs, has failed rather than succeeded.
789 + if ( '' === trim( $out ) || strlen( $out ) < ( strlen( $css ) / 20 ) ) {
790 + return $css;
791 + }
792 +
793 + return $out;
384 794 }
385 795
386 796 private static function cache_key( array $bucket ): string {
387 797 $signature = array();