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