Skip to content

Commit

Permalink
Prevent loading SDKs multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
philip-luther committed Nov 22, 2024
1 parent 6969c4f commit 74412b6
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,34 @@ export function queryString (object) {

// Util function to load an external SDK
// or return the SDK if it is already loaded
const resolves = {}
export function getSDK (url, sdkGlobal, sdkReady = null, isLoaded = () => true) {
if (window[sdkGlobal] && isLoaded(window[sdkGlobal])) {
return Promise.resolve(window[sdkGlobal])
}
return new Promise((resolve, reject) => {
// If we are already loading the SDK, add the resolve
// function to the existing array of resolve functions
if (resolves[url]) {
resolves[url].push(resolve)
return
}
resolves[url] = [resolve]
const onLoaded = sdk => {
// When loaded, resolve all pending promises
resolves[url].forEach(resolve => resolve(sdk))
}
if (sdkReady) {
const previousOnReady = window[sdkReady]
window[sdkReady] = function () {
if (previousOnReady) previousOnReady()
resolve(window[sdkGlobal])
onLoaded(window[sdkGlobal])
}
}
loadScript(url, err => {
if (err) reject(err)
if (!sdkReady) {
resolve(window[sdkGlobal])
onLoaded(window[sdkGlobal])
}
})
})
Expand Down

0 comments on commit 74412b6

Please sign in to comment.