Prevent Mini Cart loading the same script twice (https://github.com/woocommerce/woocommerce-blocks/pull/7794)
This commit is contained in:
parent
796e952b92
commit
9f3d61e1ea
|
@ -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;
|
||||
};
|
||||
|
||||
|
@ -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' );
|
||||
|
@ -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();
|
||||
}
|
||||
|
||||
|
|
|
@ -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' );
|
||||
|
|
Loading…
Reference in New Issue