Skip to content

Commit

Permalink
load synchronously if possible
Browse files Browse the repository at this point in the history
  • Loading branch information
goto-bus-stop committed May 1, 2022
1 parent 7097029 commit 968ed15
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 13 deletions.
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ function useYouTube(container, {
let instance = null;
let cancelled = false;

loadSdk().then(() => {
loadSdk(() => {
if (!cancelled) {
instance = createPlayer.current();
}
Expand Down
18 changes: 8 additions & 10 deletions src/loadSdk.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,6 @@

function loadSdk() {
return new Promise((resolve, reject) => {
if (typeof window.YT === 'object' && typeof window.YT.ready === 'function') {
// A YouTube SDK is already loaded, so reuse that
window.YT.ready(resolve);
return;
}

const script = document.createElement('script');
script.async = true;
script.src = 'https://www.youtube.com/iframe_api';
Expand All @@ -27,9 +21,13 @@ function loadSdk() {
}

let sdk = null;
export default function getSdk() {
if (!sdk) {
sdk = loadSdk();
export default function getSdk(callback) {
if (typeof window.YT === 'object' && typeof window.YT.ready === 'function') {
// A YouTube SDK is already loaded, so reuse that
window.YT.ready(callback);
return;
}
return sdk;

sdk ??= loadSdk();
sdk.then(callback);
}
4 changes: 2 additions & 2 deletions test/util/createYouTube.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ export default function createYouTube() {

const YouTube = proxyquire('../../src/index.js', {
'./loadSdk': {
default() {
default(callback) {
global.YT = sdkMock;
return Promise.resolve(sdkMock);
setImmediate(() => callback(sdkMock));
},
},
}).default;
Expand Down

0 comments on commit 968ed15

Please sign in to comment.