@draconides/youtube-iframe
Version:
YouTube API iFrame Wrapper
47 lines (46 loc) • 1.47 kB
JavaScript
const state = {
loading: false,
loaded: false,
callback: [],
};
/**
* Get a typed YouTube api object.
* This function will add YouTube iframe api into the dom if not present
* @returns - Return a Promise of YT
* @version 1.0.0
* @since 1.0.0
*/
export const YouTubeIFrameAPI = () => {
return new Promise((resolve) => {
if (state.loaded) {
resolve(window.YT);
}
if (state.loading) {
state.callback.push(resolve);
}
if (!state.loaded && !state.loading) {
state.loading = true;
state.callback.push(resolve);
window.onYouTubeIframeAPIReady = () => {
state.loaded = true;
state.loading = false;
while (state.callback.length > 0) {
const callback = state.callback.pop();
if (callback !== undefined) {
callback(window.YT);
}
}
};
if (typeof window.YT === 'undefined' ||
typeof window.YT.Player === 'undefined') {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.youtube.com/iframe_api';
document.head.appendChild(script);
}
else {
window.onYouTubeIframeAPIReady();
}
}
});
};