UNPKG

@draconides/youtube-iframe

Version:
51 lines (50 loc) 1.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.YouTubeIFrameAPI = void 0; 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 */ 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(); } } }); }; exports.YouTubeIFrameAPI = YouTubeIFrameAPI;