2020-06-08

Youtube iFrame API - YT.Player is not a constructor

javascript, youtube, iframe, error

banner

Image by SplitShire from Pixabay


title: Youtube iFrame API - YT.Player is not a constructor date: "2020-06-08" published: true tags: "javascript, youtube, iframe, error" author: Sung M. Kim banner: ./images/featured-image.jpg bannerCredit: "Image by SplitShire from Pixabay"

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.

1new YT.Player("player", {2  height: "390",3  width: "640",4  videoId: "M7lc1UVf-VE",5  events: {6    onReady: onPlayerReady,7    onStateChange: onPlayerStateChange,8  },9});

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.

1function setupPlayer() {2  /**3   * THIS FAILS!!!!!4   */5  // player = new YT.Player("player", {6  //   height: "390",7  //   width: "640",8  //   videoId: "M7lc1UVf-VE",9  //   events: {10  //     onReady: onPlayerReady,11  //     onStateChange: onPlayerStateChange12  //   }13  // });14
15  /**16   * Need to wait until Youtube Player is ready!17   */18  window.YT.ready(function () {19    player = new window.YT.Player("video", {20      height: "390",21      width: "640",22      videoId: "M7lc1UVf-VE",23      events: {24        onReady: onPlayerReady,25        onStateChange: onPlayerStateChange,26      },27    });28  });29}

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