← Go Back

Youtube iFrame API - YT.Player is not a constructor

Broken Post?Let me know

As I was playing around with YouTube Player API Reference for iframe Embeds, I was getting the following error,

TypeError
YT.Player is not a constructor

The error occurred when I was creating a new YT.Player instance.

new YT.Player("player", {
  height: "390",
  width: "640",
  videoId: "M7lc1UVf-VE",
  events: {
    onReady: onPlayerReady,
    onStateChange: onPlayerStateChange
  }
});

I was looking at this reply for the question, Uncaught TypeError: YT.Player is not a constructor but it didn't really answer what the "fix" is.

After some digging I found a working CodeSandbox sandbox, https://codesandbox.io/s/youtube-iframe-api-tpjwj (this uses jQuery), which used a undocumented API, YT.ready().

It seems to wait until the player instance is "ready" to be created similar to DOMContentLoaded for DOM.

So the fix it to wait within the callback of YT.ready.

 function setupPlayer() {
    /**
     * THIS FAILS!!!!!
     */
    // player = new YT.Player("player", {
    //   height: "390",
    //   width: "640",
    //   videoId: "M7lc1UVf-VE",
    //   events: {
    //     onReady: onPlayerReady,
    //     onStateChange: onPlayerStateChange
    //   }
    // });

    /**
     * Need to wait until Youtube Player is ready!
     */
    window.YT.ready(function() {
      player = new window.YT.Player("video", {
        height: "390",
        width: "640",
        videoId: "M7lc1UVf-VE",
        events: {
          onReady: onPlayerReady,
          onStateChange: onPlayerStateChange
        }
      });
    });
  }

The working Sandbox (I converted the jQuery version to Vanillia JS) - https://codesandbox.io/s/soanswer52062169-mem83?file=/src/index.js:406-1242


Image by SplitShire from Pixabay

Webmentions

Loading counts...

❤️ 0 💬 0
Fetching Replies...
There is no reply...