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