PageSourceSearch

https://sunnyhock.com/wp-content/themes/zousanrecordspro/js/lite-yt-embed.js

js sunnyhock.com collected 2026-10-06 18:42:49 UTC 6,819 bytes, 179 lines download raw bytes

1/**
2 * A lightweight youtube embed. Still should feel the same to the user, just MUCH faster to initialize and paint.
3 *
4 * Thx to these as the inspiration
5 *   https://storage.googleapis.com/amp-vs-non-amp/youtube-lazy.html
6 *   https://autoplay-youtube-player.glitch.me/
7 *
8 * Once built it, I also found these:
9 *   https://github.com/ampproject/amphtml/blob/master/extensions/amp-youtube (👍👍)
10 *   https://github.com/Daugilas/lazyYT
11 *   https://github.com/vb/lazyframe
12 */
13class LiteYTEmbed extends HTMLElement {
14  connectedCallback() {
15    this.videoId = this.getAttribute('videoid');
16
17    let playBtnEl = this.querySelector('.lty-playbtn');
18    // A label for the button takes priority over a [playlabel] attribute on the custom-element
19    this.playLabel =
20      (playBtnEl && playBtnEl.textContent.trim()) ||
21      this.getAttribute('playlabel') ||
22      'Play';
23
24    /**
25     * Lo, the youtube placeholder image!  (aka the thumbnail, poster image, etc)
26     *
27     * See https://github.com/paulirish/lite-youtube-embed/blob/master/youtube-thumbnail-urls.md
28     *
29     * TODO: Do the sddefault->hqdefault fallback
30     *       - When doing this, apply referrerpolicy (https://github.com/ampproject/amphtml/pull/3940)
31     * TODO: Consider using webp if supported, falling back to jpg
32     */
33    if (!this.style.backgroundImage) {
34      this.style.backgroundImage = `url("https://i.ytimg.com/vi/${this.videoId}/maxresdefault.jpg")`;
35    }
36
37    // Set up play button, and its visually hidden label
38    if (!playBtnEl) {
39      playBtnEl = document.createElement('button');
40      playBtnEl.type = 'button';
41      playBtnEl.classList.add('lty-playbtn');
42      this.append(playBtnEl);
43    }
44    if (!playBtnEl.textContent) {
45      const playBtnLabelEl = document.createElement('span');
46      playBtnLabelEl.className = 'lyt-visually-hidden';
47      playBtnLabelEl.textContent = this.playLabel;
48      playBtnEl.append(playBtnLabelEl);
49    }
50    playBtnEl.removeAttribute('href');
51
52    // On hover (or tap), warm up the TCP connections we're (likely) about to use.
53    this.addEventListener('pointerover', LiteYTEmbed.warmConnections, {
54      once: true,
55    });
56
57    // Once the user clicks, add the real iframe and drop our play button
58    // TODO: In the future we could be like amp-youtube and silently swap in the iframe during idle time
59    //   We'd want to only do this for in-viewport or near-viewport ones: https://github.com/ampproject/amphtml/pull/5003
60    this.addEventListener('click', this.addIframe);
61
62    // Chrome & Edge desktop have no problem with the basic YouTube Embed with ?autoplay=1
63    // However Safari desktop and most/all mobile browsers do not successfully track the user gesture of clicking through the creation/loading of the iframe,
64    // so they don't autoplay automatically. Instead we must load an additional 2 sequential JS files (1KB + 165KB) (un-br) for the YT Player API
65    // TODO: Try loading the the YT API in parallel with our iframe and then attaching/playing it. #82
66    this.needsYTApiForAutoplay =
67      navigator.vendor.includes('Apple') ||
68      navigator.userAgent.includes('Mobi');
69  }
70
71  /**
72   * Add a <link rel={preload | preconnect} ...> to the head
73   */
74  static addPrefetch(kind, url, as) {
75    const linkEl = document.createElement('link');
76    linkEl.rel = kind;
77    linkEl.href = url;
78    if (as) {
79      linkEl.as = as;
80    }
81    document.head.append(linkEl);
82  }
83
84  /**
85   * Begin pre-connecting to warm up the iframe load
86   * Since the embed's network requests load within its iframe,
87   *   preload/prefetch'ing them outside the iframe will only cause double-downloads.
88   * So, the best we can do is warm up a few connections to origins that are in the critical path.
89   *
90   * Maybe `<link rel=preload as=document>` would work, but it's unsupported: http://crbug.com/593267
91   * But TBH, I don't think it'll happen soon with Site Isolation and split caches adding serious complexity.
92   */
93  static warmConnections() {
94    if (LiteYTEmbed.preconnected) return;
95
96    // The iframe document and most of its subresources come right off youtube.com
97    LiteYTEmbed.addPrefetch('preconnect', 'https://www.youtube-nocookie.com');
98    // The botguard script is fetched off from google.com
99    LiteYTEmbed.addPrefetch('preconnect', 'https://www.google.com');
100
101    // Not certain if these ad related domains are in the critical path. Could verify with domain-specific throttling.
102    LiteYTEmbed.addPrefetch(
103      'preconnect',
104      'https://googleads.g.doubleclick.net'
105    );
106    LiteYTEmbed.addPrefetch('preconnect', 'https://static.doubleclick.net');
107
108    LiteYTEmbed.preconnected = true;
109  }
110
111  fetchYTPlayerApi() {
112    if (window.YT || (window.YT && window.YT.Player)) return;
113
114    this.ytApiPromise = new Promise((res, rej) => {
115      var el = document.createElement('script');
116      el.src = 'https://www.youtube.com/iframe_api';
117      el.async = true;
118      el.onload = (_) => {
119        YT.ready(res);
120      };
121      el.onerror = rej;
122      this.append(el);
123    });
124  }
125
126  async addYTPlayerIframe(params) {
127    this.fetchYTPlayerApi();
128    await this.ytApiPromise;
129
130    const videoPlaceholderEl = document.createElement('div');
131    this.append(videoPlaceholderEl);
132
133    const paramsObj = Object.fromEntries(params.entries());
134
135    new YT.Player(videoPlaceholderEl, {
136      width: '100%',
137      videoId: this.videoId,
138      playerVars: paramsObj,
139      events: {
140        onReady: (event) => {
141          event.target.playVideo();
142        },
143      },
144    });
145  }
146
147  async addIframe() {
148    if (this.classList.contains('lyt-activated')) return;
149    this.classList.add('lyt-activated');
150
151    const params = new URLSearchParams(this.getAttribute('params') || []);
152    params.append('autoplay', '1');
153    params.append('playsinline', '1');
154
155    if (this.needsYTApiForAutoplay) {
156      return this.addYTPlayerIframe(params);
157    }
158
159    const iframeEl = document.createElement('iframe');
160    iframeEl.width = 560;
161    iframeEl.height = 315;
162    // No encoding necessary as [title] is safe. https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#:~:text=Safe%20HTML%20Attributes%20include
163    iframeEl.title = this.playLabel;
164    iframeEl.allow =
165      'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture';
166    iframeEl.allowFullscreen = true;
167    // AFAIK, the encoding here isn't necessary for XSS, but we'll do it only because this is a URL
168    // https://stackoverflow.com/q/64959723/89484
169    iframeEl.src = `https://www.youtube-nocookie.com/embed/${encodeURIComponent(
170      this.videoId
171    )}?${params.toString()}`;
172    this.append(iframeEl);
173
174    // Set focus for a11y
175    iframeEl.focus();
176  }
177}
178// Register custom element
179customElements.define('lite-youtube', LiteYTEmbed);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.