Created
August 20, 2020 12:06
-
-
Save luislobo14rap/d2bad5aa6600343abb58f7c29905ce3d to your computer and use it in GitHub Desktop.
youtube-iframe-faster.js
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
// youtube-iframe-faster.js v1 | |
function youtubeIframeFaster(youtubeID, userOptions = {}, callback) { | |
if (typeof youtubeID !== 'string'){ | |
return console.error('The youtubeID argument is required and must be of the type string.'); | |
}; | |
let element = document.querySelector(`#${youtubeID}`), | |
options = { // everyone is boolean | |
autoplay: false, | |
autoTitle: true, // iframe attribute title="${videoTitle}" | |
loop: false, | |
mute: false, | |
removeSizes: true // remove height and width attributes | |
}; | |
if (element && element.tagName !== 'IFRAME') { | |
for (key in userOptions) { // extend | |
options[key] = userOptions[key]; | |
}; | |
if (!document.querySelector('script[src*="youtube.com/iframe_api"]')) { | |
let script = document.createElement('script'), | |
protocol = window.location.protocol; | |
if(protocol.substring(0, 4) !== 'http'){ // only accepts http and https | |
protocol = 'https:'; | |
}; | |
script.setAttribute('src', protocol + '//www.youtube.com/player_api'); | |
let firstElement = document.querySelector('script') || document.querySelector('head'); | |
if(firstElement.tagName === 'SCRIPT'){ | |
firstElement.parentNode.insertBefore(script, firstElement); | |
}else{ | |
firstElement.append(script); | |
}; | |
}; | |
let waitYT = setInterval(() => { | |
if (window.YT && window.YT.loaded === 1) { | |
clearInterval(waitYT); | |
let player = new YT.Player(youtubeID, { | |
videoId: youtubeID, | |
events: { | |
onReady: function(event){ | |
let title = event.target.getVideoData().title; | |
element = event.target.f; // updates the element reference | |
if(options.removeSizes == true){ | |
element.removeAttribute('height'); | |
element.removeAttribute('width'); | |
}; | |
if(options.autoTitle){ | |
element.setAttribute('title', title); | |
}; | |
if (options.mute == true) { | |
player.mute(); | |
}; | |
if (options.autoplay == true) { | |
player.playVideo(); | |
}; | |
if(callback){ | |
callback({ | |
element, | |
options, | |
player, | |
title, | |
youtubeID | |
}); | |
}; | |
}, | |
onStateChange: function(event){ | |
if (options.loop == true) { | |
if (player.getCurrentTime() === player.getDuration()) { | |
player.seekTo(0); | |
player.playVideo(); | |
}; | |
}; | |
} | |
} | |
}); | |
}; | |
}, 50); | |
}else{ | |
if(element){ | |
console.error('The element cannot be an iframe'); | |
}else{ | |
console.error('Element not found'); | |
}; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment