2021-12-07 10:07:32 +00:00
|
|
|
interface PreloadScriptParams {
|
2021-08-25 15:42:55 +00:00
|
|
|
handle: string;
|
|
|
|
src: string;
|
|
|
|
version?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Appends a `<link>` tag to the document head to preload a script based on the
|
|
|
|
* src and handle parameters.
|
|
|
|
*/
|
|
|
|
const preloadScript = ( {
|
|
|
|
handle,
|
|
|
|
src,
|
|
|
|
version,
|
2021-12-07 10:07:32 +00:00
|
|
|
}: PreloadScriptParams ): void => {
|
2022-12-01 10:54:28 +00:00
|
|
|
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 );
|
2021-08-25 15:42:55 +00:00
|
|
|
|
|
|
|
if ( handleScriptElements.length === 0 ) {
|
|
|
|
const prefetchLink = document.createElement( 'link' );
|
2021-09-08 11:17:30 +00:00
|
|
|
prefetchLink.href = version ? `${ src }?ver=${ version }` : src;
|
2021-08-25 15:42:55 +00:00
|
|
|
prefetchLink.rel = 'preload';
|
|
|
|
prefetchLink.as = 'script';
|
|
|
|
prefetchLink.id = `${ handle }-js-prefetch`;
|
|
|
|
document.head.appendChild( prefetchLink );
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
export default preloadScript;
|