Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. */
  13. class LiteYTEmbed extends HTMLElement {
  14. connectedCallback() {
  15. this.videoId = this.getAttribute('videoid');
  16. let playBtnEl = this.querySelector('.lyt-playbtn,.lty-playbtn');
  17. // A label for the button takes priority over a [playlabel] attribute on the custom-element
  18. this.playLabel = (playBtnEl && playBtnEl.textContent.trim()) || this.getAttribute('playlabel') || 'Play';
  19. this.dataset.title = this.getAttribute('title') || "";
  20. /**
  21. * Lo, the youtube poster image! (aka the thumbnail, image placeholder, etc)
  22. *
  23. * See https://github.com/paulirish/lite-youtube-embed/blob/master/youtube-thumbnail-urls.md
  24. */
  25. if (!this.style.backgroundImage) {
  26. this.style.backgroundImage = `url("https://i.ytimg.com/vi/${this.videoId}/hqdefault.jpg")`;
  27. this.upgradePosterImage();
  28. }
  29. // Set up play button, and its visually hidden label
  30. if (!playBtnEl) {
  31. playBtnEl = document.createElement('button');
  32. playBtnEl.type = 'button';
  33. // Include the mispelled 'lty-' in case it's still being used. https://github.com/paulirish/lite-youtube-embed/issues/65
  34. playBtnEl.classList.add('lyt-playbtn', 'lty-playbtn');
  35. this.append(playBtnEl);
  36. }
  37. if (!playBtnEl.textContent) {
  38. const playBtnLabelEl = document.createElement('span');
  39. playBtnLabelEl.className = 'lyt-visually-hidden';
  40. playBtnLabelEl.textContent = this.playLabel;
  41. playBtnEl.append(playBtnLabelEl);
  42. }
  43. this.addNoscriptIframe();
  44. // for the PE pattern, change anchor's semantics to button
  45. if(playBtnEl.nodeName === 'A'){
  46. playBtnEl.removeAttribute('href');
  47. playBtnEl.setAttribute('tabindex', '0');
  48. playBtnEl.setAttribute('role', 'button');
  49. // fake button needs keyboard help
  50. playBtnEl.addEventListener('keydown', e => {
  51. if( e.key === 'Enter' || e.key === ' ' ){
  52. e.preventDefault();
  53. this.activate();
  54. }
  55. });
  56. }
  57. // On hover (or tap), warm up the TCP connections we're (likely) about to use.
  58. this.addEventListener('pointerover', LiteYTEmbed.warmConnections, {once: true});
  59. this.addEventListener('focusin', LiteYTEmbed.warmConnections, {once: true});
  60. // Once the user clicks, add the real iframe and drop our play button
  61. // TODO: In the future we could be like amp-youtube and silently swap in the iframe during idle time
  62. // We'd want to only do this for in-viewport or near-viewport ones: https://github.com/ampproject/amphtml/pull/5003
  63. this.addEventListener('click', this.activate);
  64. // Chrome & Edge desktop have no problem with the basic YouTube Embed with ?autoplay=1
  65. // However Safari desktop and most/all mobile browsers do not successfully track the user gesture of clicking through the creation/loading of the iframe,
  66. // 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
  67. // TODO: Try loading the the YT API in parallel with our iframe and then attaching/playing it. #82
  68. this.needsYTApi = this.hasAttribute("js-api") || navigator.vendor.includes('Apple') || navigator.userAgent.includes('Mobi');
  69. }
  70. /**
  71. * Add a <link rel={preload | preconnect} ...> to the head
  72. */
  73. static addPrefetch(kind, url, as) {
  74. const linkEl = document.createElement('link');
  75. linkEl.rel = kind;
  76. linkEl.href = url;
  77. if (as) {
  78. linkEl.as = as;
  79. }
  80. document.head.append(linkEl);
  81. }
  82. /**
  83. * Begin pre-connecting to warm up the iframe load
  84. * Since the embed's network requests load within its iframe,
  85. * preload/prefetch'ing them outside the iframe will only cause double-downloads.
  86. * So, the best we can do is warm up a few connections to origins that are in the critical path.
  87. *
  88. * Maybe `<link rel=preload as=document>` would work, but it's unsupported: http://crbug.com/593267
  89. * But TBH, I don't think it'll happen soon with Site Isolation and split caches adding serious complexity.
  90. */
  91. static warmConnections() {
  92. if (LiteYTEmbed.preconnected) return;
  93. // The iframe document and most of its subresources come right off youtube.com
  94. LiteYTEmbed.addPrefetch('preconnect', 'https://www.youtube-nocookie.com');
  95. // The botguard script is fetched off from google.com
  96. LiteYTEmbed.addPrefetch('preconnect', 'https://www.google.com');
  97. // Not certain if these ad related domains are in the critical path. Could verify with domain-specific throttling.
  98. LiteYTEmbed.addPrefetch('preconnect', 'https://googleads.g.doubleclick.net');
  99. LiteYTEmbed.addPrefetch('preconnect', 'https://static.doubleclick.net');
  100. LiteYTEmbed.preconnected = true;
  101. }
  102. fetchYTPlayerApi() {
  103. if (window.YT || (window.YT && window.YT.Player)) return;
  104. this.ytApiPromise = new Promise((res, rej) => {
  105. var el = document.createElement('script');
  106. el.src = 'https://www.youtube.com/iframe_api';
  107. el.async = true;
  108. el.onload = _ => {
  109. YT.ready(res);
  110. };
  111. el.onerror = rej;
  112. this.append(el);
  113. });
  114. }
  115. /** Return the YT Player API instance. (Public L-YT-E API) */
  116. async getYTPlayer() {
  117. if(!this.playerPromise) {
  118. await this.activate();
  119. }
  120. return this.playerPromise;
  121. }
  122. async addYTPlayerIframe() {
  123. this.fetchYTPlayerApi();
  124. await this.ytApiPromise;
  125. const videoPlaceholderEl = document.createElement('div')
  126. this.append(videoPlaceholderEl);
  127. const paramsObj = Object.fromEntries(this.getParams().entries());
  128. this.playerPromise = new Promise(resolve => {
  129. let player = new YT.Player(videoPlaceholderEl, {
  130. width: '100%',
  131. videoId: this.videoId,
  132. playerVars: paramsObj,
  133. events: {
  134. 'onReady': event => {
  135. event.target.playVideo();
  136. resolve(player);
  137. }
  138. }
  139. });
  140. });
  141. }
  142. // Add the iframe within <noscript> for indexability discoverability. See https://github.com/paulirish/lite-youtube-embed/issues/105
  143. addNoscriptIframe() {
  144. const iframeEl = this.createBasicIframe();
  145. const noscriptEl = document.createElement('noscript');
  146. // Appending into noscript isn't equivalant for mysterious reasons: https://html.spec.whatwg.org/multipage/scripting.html#the-noscript-element
  147. noscriptEl.innerHTML = iframeEl.outerHTML;
  148. this.append(noscriptEl);
  149. }
  150. getParams() {
  151. const params = new URLSearchParams(this.getAttribute('params') || []);
  152. params.append('autoplay', '1');
  153. params.append('playsinline', '1');
  154. return params;
  155. }
  156. async activate(){
  157. if (this.classList.contains('lyt-activated')) return;
  158. this.classList.add('lyt-activated');
  159. if (this.needsYTApi) {
  160. return this.addYTPlayerIframe(this.getParams());
  161. }
  162. const iframeEl = this.createBasicIframe();
  163. this.append(iframeEl);
  164. // Set focus for a11y
  165. iframeEl.focus();
  166. }
  167. createBasicIframe(){
  168. const iframeEl = document.createElement('iframe');
  169. iframeEl.width = 560;
  170. iframeEl.height = 315;
  171. // No encoding necessary as [title] is safe. https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#:~:text=Safe%20HTML%20Attributes%20include
  172. iframeEl.title = this.playLabel;
  173. iframeEl.allow = 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture';
  174. iframeEl.allowFullscreen = true;
  175. // AFAIK, the encoding here isn't necessary for XSS, but we'll do it only because this is a URL
  176. // https://stackoverflow.com/q/64959723/89484
  177. iframeEl.src = `https://www.youtube-nocookie.com/embed/${encodeURIComponent(this.videoId)}?${this.getParams().toString()}`;
  178. return iframeEl;
  179. }
  180. /**
  181. * In the spirit of the `lowsrc` attribute and progressive JPEGs, we'll upgrade the reliable
  182. * poster image to a higher resolution one, if it's available.
  183. * Interestingly this sddefault webp is often smaller in filesize, but we will still attempt it second
  184. * because getting _an_ image in front of the user if our first priority.
  185. *
  186. * See https://github.com/paulirish/lite-youtube-embed/blob/master/youtube-thumbnail-urls.md for more details
  187. */
  188. upgradePosterImage() {
  189. // Defer to reduce network contention.
  190. setTimeout(() => {
  191. const webpUrl = `https://i.ytimg.com/vi_webp/${this.videoId}/sddefault.webp`;
  192. const img = new Image();
  193. img.fetchPriority = 'low'; // low priority to reduce network contention
  194. img.referrerpolicy = 'origin'; // Not 100% sure it's needed, but https://github.com/ampproject/amphtml/pull/3940
  195. img.src = webpUrl;
  196. img.onload = e => {
  197. // A pretty ugly hack since onerror won't fire on YouTube image 404. This is (probably) due to
  198. // Youtube's style of returning data even with a 404 status. That data is a 120x90 placeholder image.
  199. // … per "annoying yt 404 behavior" in the .md
  200. const noAvailablePoster = e.target.naturalHeight == 90 && e.target.naturalWidth == 120;
  201. if (noAvailablePoster) return;
  202. this.style.backgroundImage = `url("${webpUrl}")`;
  203. }
  204. }, 100);
  205. }
  206. }
  207. // Register custom element
  208. customElements.define('lite-youtube', LiteYTEmbed);