From b53826307c57d6c591de3fc820dcb1517b1d8978 Mon Sep 17 00:00:00 2001 From: webmiraclepro Date: Mon, 14 May 2018 06:03:46 +0800 Subject: [PATCH] Prevent loading SDKs multiple times Fixes https://github.com/CookPete/react-player/issues/391 --- src/utils.js | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/utils.js b/src/utils.js index 132ee5a..82d89e6 100644 --- a/src/utils.js +++ b/src/utils.js @@ -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]) } }) })