Skip to content

Commit

Permalink
choree: script-loader 분기마다 주석 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
moresoo committed Jun 28, 2024
1 parent a9b4eb6 commit 4a32501
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/sdk-loader/src/loadScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,25 @@ interface LoadOptions {
}

export function loadScript<Namespace>(src: string, namespace: string, options: LoadOptions = {}): Promise<Namespace> {
// Return the cached Promise if it exists
if (cachedPromise != null) {
return cachedPromise;
}

const promise = new Promise((resolve, reject) => {
try {
// Handle SSR
if (typeof window === 'undefined' || typeof document === 'undefined') {
return resolve(null);
}

// If the SDK instance already exists in the global namespace, resolve with it
if (getNamespace(namespace) != null) {
return resolve(getNamespace<Namespace>(namespace));
}

// if script exists, but we are reloading due to an error,
// reload script to trigger 'load' event
const existingScript = document.querySelector(`script[src="${src}"]`);
if (existingScript != null) {
existingScript.removeEventListener('load', onLoad);
Expand Down Expand Up @@ -54,6 +59,7 @@ export function loadScript<Namespace>(src: string, namespace: string, options: L
}
});

// Reset the cache if the Promise is rejected
cachedPromise = promise.catch(error => {
cachedPromise = null;
return Promise.reject(error);
Expand Down

0 comments on commit 4a32501

Please sign in to comment.