Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
Remove wc-blocks-registry from Mini Cart block dependencies so more s…
Browse files Browse the repository at this point in the history
…cripts 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
  • Loading branch information
Aljullu authored Mar 8, 2023
1 parent 24d368d commit cb8b1ed
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
18 changes: 18 additions & 0 deletions assets/js/base/utils/lazy-load-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,31 @@ 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:
* `<script src='...' id='[SCRIPT_ID]'></script>`
* This function checks whether an element matching that selector exists.
* 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 ];
Expand Down
4 changes: 2 additions & 2 deletions src/BlockTypes/MiniCart.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -282,7 +282,7 @@ protected function append_script_and_deps_src( $script ) {
}
}
}
if ( ! $script->src || 'wc-blocks-registry' === $script->handle ) {
if ( ! $script->src ) {
return;
}

Expand Down

0 comments on commit cb8b1ed

Please sign in to comment.