From cb8b1ed296b8c45ef37f8648b092f5c40a491d9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Albert=20Juh=C3=A9=20Lluveras?= Date: Wed, 8 Mar 2023 17:15:07 +0100 Subject: [PATCH] Remove wc-blocks-registry from Mini Cart block dependencies so more scripts can be lazy-loaded (#8657) * Remove wc-blocks-registry from Mini Cart block so more scripts can be lazy-loaded * Make check more reliable in case window.wc is not defined --- assets/js/base/utils/lazy-load-script.ts | 18 ++++++++++++++++++ src/BlockTypes/MiniCart.php | 4 ++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/assets/js/base/utils/lazy-load-script.ts b/assets/js/base/utils/lazy-load-script.ts index 9758ecfd7f6..2a282dbef71 100644 --- a/assets/js/base/utils/lazy-load-script.ts +++ b/assets/js/base/utils/lazy-load-script.ts @@ -20,6 +20,14 @@ interface AppendScriptAttributesParam { src?: string; } +declare global { + interface Window { + wc: { + wcBlocksRegistry: Record< string, unknown >; + }; + } +} + /** * In WP, registered scripts are loaded into the page with an element like this: * `` @@ -27,6 +35,16 @@ interface AppendScriptAttributesParam { * Useful to know if a script has already been appended to the page. */ const isScriptTagInDOM = ( scriptId: string, src = '' ): boolean => { + // If the store is using a plugin to concatenate scripts, we might have some + // cases where we don't detect whether a script has already been loaded. + // Because of that, we add an extra protection to the wc-blocks-registry-js + // script, to avoid ending up with two registries. + if ( scriptId === 'wc-blocks-registry-js' ) { + if ( typeof window?.wc?.wcBlocksRegistry === 'object' ) { + return true; + } + } + const srcParts = src.split( '?' ); if ( srcParts?.length > 1 ) { src = srcParts[ 0 ]; diff --git a/src/BlockTypes/MiniCart.php b/src/BlockTypes/MiniCart.php index 6d5e054cdc5..64f4b44bc00 100644 --- a/src/BlockTypes/MiniCart.php +++ b/src/BlockTypes/MiniCart.php @@ -103,7 +103,7 @@ protected function get_block_type_script( $key = null ) { $script = [ 'handle' => 'wc-' . $this->block_name . '-block-frontend', 'path' => $this->asset_api->get_block_asset_build_path( $this->block_name . '-frontend' ), - 'dependencies' => [ 'wc-blocks-registry' ], + 'dependencies' => [], ]; return $key ? $script[ $key ] : $script; } @@ -282,7 +282,7 @@ protected function append_script_and_deps_src( $script ) { } } } - if ( ! $script->src || 'wc-blocks-registry' === $script->handle ) { + if ( ! $script->src ) { return; }