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