Created
July 31, 2018 07:09
-
-
Save cravindra/81d1339640e70637a41d5345ec379f75 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Helper to inject the YouTube iFrame API script and initialise a YouTube video | |
* @param container {DOMElement | string} A Dom element or a string which is the id of the element to make a youtube video | |
* @param [playerOptions={}] {Object} An object as defined by the [YT iFrame API](https://developers.google.com/youtube/player_parameters) | |
*/ | |
export default function inject(container, playerOptions={}) { | |
// Extract Player vars if available | |
const playerVars = {...(playerOptions.playerVars || {})}; | |
delete playerOptions.playerVars; | |
// Rebuild playerOptions objects with overrides provided | |
playerOptions = { | |
height: '100%', | |
width: '100%', | |
playerVars:{ | |
rel: 0, | |
modestbranding: 1, | |
fs: 0, | |
origin: window.location.origin, | |
...playerVars | |
}, | |
...playerOptions | |
}; | |
return new Promise(resolve => { | |
// Check if YouTube iFrame API is available on the page | |
if (!window.YT) { | |
// No YT object found | |
// Check if YT iframe API script has been injected | |
if (!window.ytScriptInjected) { | |
// Script injection pending, inject scripts and update flag to indicate as such | |
const tag = document.createElement('script') | |
tag.src = 'https://www.youtube.com/iframe_api' | |
const firstScriptTag = document.getElementsByTagName('script')[0] | |
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag) | |
window.ytScriptInjected = true | |
} | |
// Store callbacks registered earlier | |
const oldOnReady = window.onYouTubeIframeAPIReady | |
// Define the callback to handle when the YT iframe API has loaded | |
window.onYouTubeIframeAPIReady = function() { | |
// Check if an older callback had been registered and call it if needed | |
oldOnReady && typeof oldOnReady === 'function' && oldOnReady() | |
// Create player object | |
const player = new YT.Player(container, playerOptions) | |
// Resolve | |
resolve(player) | |
} | |
} else { | |
// YT player object is available, create player and resolve | |
const player = new YT.Player(container, playerOptions) | |
resolve(player) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment