When using the YouTube API, you are required to create the function onYouTubePlayerAPIReady
. There is a huge problem with this.
If you have multiple WordPress plugins that use the YouTube API, that means that you have multiple declarations of onYouTubePlayerAPIReady
. Multiple declarations in Javascript mean that previous onYouTubePlayerAPIReady
functions get overwritten and will never be called. So if you are using 2 WordPress plugins that both use the YouTube API, 1 of them will for sure stop working.
The workaround for this is before creating your own onYouTubePlayerAPIReady
function, you should check first for previous declarations and keep a reference to those previous functions. Then inside your own onYouTubePlayerAPIReady
function, after you perform the tasks you want, call the function references you kept.
The New onYouTubePlayerAPIReady
Instead of doing simply this:
function onYouTubePlayerAPIReady() {
// Initialize YT.Player and do stuff here
}
Use this instead:
setTimeout( function() {
if ( typeof window.onYouTubePlayerAPIReady !== 'undefined' ) {
if ( typeof window.gambitOtherYTAPIReady === 'undefined' ) {
window.gambitOtherYTAPIReady = [];
}
window.gambitOtherYTAPIReady.push( window.onYouTubePlayerAPIReady );
}
window.onYouTubePlayerAPIReady = function() {
// Initialize YT.Player and do stuff here
if ( typeof window.gambitOtherYTAPIReady !== 'undefined' ) {
if ( window.gambitOtherYTAPIReady.length ) {
window.gambitOtherYTAPIReady.pop()();
}
}
}
}, 2);
Explanation
Important parts of the code:
setTimeout
– We wait a small bit until other Javascript have run and if other code elsewhere have defined a functiononYouTubePlayerAPIReady
, then we can detect that,window.gambitOtherYTAPIReady
– We create a global array/stack that we will use to store the existingonYouTubePlayerAPIReady
functions,window.onYouTubePlayerAPIReady
– We then create our ownonYouTubePlayerAPIReady
where we do what we need,window.gambitOtherYTAPIReady.pop()()
– Before the ready function ends, we call the other stored function, which in turn will call another one, and so on until they are all complete.