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

Prevent Mini Cart loading the same script twice #7794

Merged
merged 1 commit into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions assets/js/base/utils/lazy-load-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,16 @@ interface AppendScriptAttributesParam {
* 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 ): boolean => {
const scriptElements = document.querySelectorAll( `script#${ scriptId }` );
const isScriptTagInDOM = ( scriptId: string, src = '' ): boolean => {
const srcParts = src.split( '?' );
if ( srcParts?.length > 1 ) {
src = srcParts[ 0 ];
}
const selector = src
? `script#${ scriptId }, script[src*="${ src }"]`
: `script#${ scriptId }`;
const scriptElements = document.querySelectorAll( selector );

return scriptElements.length > 0;
};

Expand All @@ -37,7 +45,10 @@ const isScriptTagInDOM = ( scriptId: string ): boolean => {
*/
const appendScript = ( attributes: AppendScriptAttributesParam ): void => {
// Abort if id is not valid or a script with the same id exists.
if ( ! isString( attributes.id ) || isScriptTagInDOM( attributes.id ) ) {
if (
! isString( attributes.id ) ||
isScriptTagInDOM( attributes.id, attributes?.src )
) {
return;
}
const scriptElement = document.createElement( 'script' );
Expand Down Expand Up @@ -92,7 +103,7 @@ const lazyLoadScript = ( {
translations,
}: LazyLoadScriptParams ): Promise< void > => {
return new Promise( ( resolve, reject ) => {
if ( isScriptTagInDOM( `${ handle }-js` ) ) {
if ( isScriptTagInDOM( `${ handle }-js`, src ) ) {
resolve();
}

Expand Down
9 changes: 6 additions & 3 deletions assets/js/base/utils/preload-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@ const preloadScript = ( {
src,
version,
}: PreloadScriptParams ): void => {
const handleScriptElements = document.querySelectorAll(
`#${ handle }-js, #${ handle }-js-prefetch`
);
const srcParts = src.split( '?' );
if ( srcParts?.length > 1 ) {
src = srcParts[ 0 ];
}
const selector = `#${ handle }-js, #${ handle }-js-prefetch, script[src*="${ src }"]`;
const handleScriptElements = document.querySelectorAll( selector );

if ( handleScriptElements.length === 0 ) {
const prefetchLink = document.createElement( 'link' );
Expand Down