paulirish / lite-youtube-embed

A faster youtube embed.
https://paulirish.github.io/lite-youtube-embed/
Other
5.48k stars 259 forks source link

Types: Property 'ready' does not exist on type 'typeof YT'. #146

Open bsastregx opened 1 year ago

bsastregx commented 1 year ago

Hello. Thanks for this custom element. I am adapting the javacript code to a lit component that uses typescript. I have installed @types/youtube , and I am getting the following error:

Property 'ready' does not exist on type 'typeof YT'.

The error arises from this fragment:

  fetchYTPlayerApi() {
    if (window.YT || (window.YT && window.YT.Player)) return;

    this.ytApiPromise = new Promise((res, rej) => {
      const el = document.createElement('script');
      el.src = 'https://www.youtube.com/iframe_api';
      el.async = true;
      el.onload = (_) => {
        YT.ready(res);
      };
      el.onerror = rej;
      this.append(el);
    });
  }

I have looked up on the youtube type definition, and in fact, I don't find ready: https://www.npmjs.com/package/@types/youtube?activeTab=code

Is maybe your code outdated? Thanks in advance.

paulirish commented 9 months ago

Hmm interesting. Yeah i can't find a reference to this method in the official documentation: https://developers.google.com/youtube/iframe_api_reference

It looks like we want to use this onYouTubeIframeAPIReady global instead.


Ah.. okay we have the iframe_api script (just a loader). and then the widgetapi script that it loads.

When the widgetapi script loads and finishes its initial evaluation it has these lines:

image

First it calls back to yt_api and says "we're ready". That ends up calling any callbacks registered on YT.ready().

Right after that it calls the onYouTubeIframeAPIReady global if its defined.

(Note: flip needsYTApiForAutoplay to true to debug this on desktop)


The nice thing is that our current method plays well with having multiple embeds together on 1 page. A global complicates that.

But the downside is .. its using undocumented APIs.

Hmm... something to consider.