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