How to Use the Javascript YouTube API Across Multiple Plugins

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 ) {
}, 2);


Important parts of the code:

  1. setTimeout – We wait a small bit until other Javascript have run and if other code elsewhere have defined a function onYouTubePlayerAPIReady, then we can detect that,
  2. window.gambitOtherYTAPIReady – We create a global array/stack that we will use to store the existing onYouTubePlayerAPIReady functions,
  3. window.onYouTubePlayerAPIReady – We then create our own onYouTubePlayerAPIReady where we do what we need,
  4. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *