HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<main>
<section>
<h1>Late-load YouTube videos on demand</h1>
<p>Videos are loaded upon user interaction, not before.</p>
<p>A lightweight, accessible, and very performant, video component / module using HTML5 Custom Elements. Just the background image is loaded until it's showtime.
</p>
</section>
<section>
<h2>Single video</h2>
<yt-l class=vdo-1 hidden videoId=631k3M2Sxe4 videoTitle="Rock & Bowl festival"></yt-l>
</section>
<section class=-fullWidthBlock>
<h2>Multiple videos <span>(in a block)</span></h2>
<!--
Note: This is a list of four list items.
Use a ul, ol, or add roles to divs.
-->
<div class=video_lst role=list>
<!-- Classes are used for layout -->
<yt-l class=vdo-2 hidden role=listitem videoId=vzbXU-MhghA videoTitle="Bat the Dog: Sweet About Me"></yt-l>
<yt-l class=vdo-2 hidden role=listitem videoId=CIqM2oCru5U videoTitle="The Go Nows: Best Laid Plans"></yt-l>
<yt-l class=vdo-2 hidden role=listitem videoId=57hvbJkd_fc videoTitle="Bat the Dog: La Bamba"></yt-l>
<yt-l class=vdo-2 hidden role=listitem videoId=aNjyxudde40 videoTitle="Shalane: Jammin' on the beach"></yt-l>
</div>
</section>
<section>
<h2>Built with WCAG Accessibility in mind</h2>
<ul>
<li>Friendly to keyboard-only users</li>
<li>Accessible names are used throughout</li>
<li>The play button is labelled</li>
<li>The iframe includes a title</li>
<li>Each asset has a heading</li>
<li>Fully responsive</li>
<li>Customisable via CSS variables (Custom Properties)</li>
<li>Smoother transition between static image and video.</li>
</ul>
<h2>Why bother to do this?</h2>
<p>See the well-thought-out article: <a class=-nowrap target=_blank title="[new window]" href="https://lean.codecomputerlove.com/make-your-own-lightweight-youtube-player/">Make YouTube Embeds Load Faster</a> by Moujib Aghrout. His reasoning is very good, though personally I'd use the method presented here.</p>
</section>
<section>
<h2>That beautiful code!</h2>
<p>See the CodePen panels for annotation, this is the production friendly nitty-gritty:</p>
<figure>
<figcaption>HTML single video</figcaption>
<pre><code class=language-markup spellcheck=false contenteditable><yt-l videoId="[youtube-id]" videoTitle="[video-title]"></yt-l></code></pre>
</figure>
<figure>
<figcaption>HTML multiple video block</figcaption>
<pre><code class=language-markup spellcheck=false contenteditable><div role="list">
<yt-l role="listitem" videoId="[youtube-id]" videoTitle="[video-title]"></yt-l>
<yt-l role="listitem" videoId="[youtube-id]" videoTitle="[video-title]"></yt-l>
…
</div></code></pre>
</figure>
<figure>
<figcaption>CSS Custom Properties</figcaption>
<pre><code class=language-css spellcheck=false contenteditable>yt-l {
/* Exposed "globally-scoped" custom properties: */
/* These are the default values */
/* They don't need to be defined, and may be overridden */
--aspectRatio: calc(100% / (16 / 9));
--overlayBgImg: linear-gradient(0, rgba(0,0,0,.4) 6%, rgba(0,0,0,0) 50%, rgba(0,0,0,.4) 100%);
--btnSize: 3rem;
--titleColor: #fff;
--titleBgColor: #000;
--titleFont: 1rem/1 sans-serif;
--titlePadding: .25rem;
}</code></pre>
</figure>
<figure>
<figcaption>JavaScript ES6 <small>[5.22 KB - 2.58 KB gzipped]</small></figcaption>
<pre><code class=language-js spellcheck=false contenteditable>const template=document.createElement('template');template.innerHTML=`<style>:host{--aspectRatio:calc(100% / (16 / 9));--overlayBgImg:linear-gradient(0, rgba(0,0,0,.4) 6%, rgba(0,0,0,0) 50%, rgba(0,0,0,.4) 100%);--btnHeight:3rem;--titleColor:#fff;--titleBgColor:#000;--titleFont:1rem/1 sans-serif;--titlePadding:.25rem;display:block;position:relative;contain:content;cursor:pointer}.ytl::before,.ytl_btn-play,.ytl_svg{position:absolute}.ytl::before{content:'';width:100%;height:100%;background-image:var(--overlayBgImg);transition:opacity .3s ease-out}.ytl:focus-within::before,.ytl:hover::before{opacity:0}.ytl::after{content:"";display:block;padding-bottom:var(--aspectRatio)}.ytl_btn-play::-moz-focus-inner{border:0}.ytl_btn-play{display:block;width:100%;height:100%;background-color:transparent;border:none;padding:0;cursor:pointer}.ytl_svg{display:block;top:50%;left:50%;width:calc(var(--btnHeight) * 1.42);height:var(--btnHeight);transform-origin:50% 50%;z-index:1;transform:translate3d(-50%,-50%,0)}.ytl_iframe,.ytl_title{position:absolute;width:100%}.ytl_path-playBg{fill:hsla(0,0%,0%,.5);transition:fill .3s ease-out}.ytl_btn-play:focus .ytl_path-playBg,.ytl_btn-play:hover .ytl_path-playBg{fill:hsla(0,100%,50%,1);outline:0}.ytl_title{bottom:0;color:var(--titleColor);background-color:var(--titleBgColor);font:var(--titleFont);text-align:center;margin:0;padding:var(--titlePadding);transition:opacity .3s ease-out,visibility 0s ease-out .3s}.ytl_iframe{height:100%;top:0;left:0;opacity:0;transition:opacity 1s ease-out}.-js-loading .ytl_svg{transform:translate3d(-50%,-50%,0) scale(1.6);opacity:.7}.ytl_path-loading{display:none;transform-origin:50% 50%;animation:rotating 1s linear infinite}.-js-loading .ytl_path-loading{display:block}.-js-loading .ytl_path-play{display:none}@keyframes rotating{from{transform:rotate(0)}to{transform:rotate(360deg)}}.-js-loaded{cursor:unset}.-js-loaded>.ytl_iframe{opacity:1}.-js-loaded::before,.-js-loaded>.ytl_btn-play,.-js-loaded>.ytl_title{visibility:hidden;opacity:0}</style>`;
class YouTubeLiteEmbed extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"});const e=this.shadowRoot;e.appendChild(template.content.cloneNode(!0)),e.videoId=encodeURIComponent(this.getAttribute("videoid")),e.heading=this.getAttribute("videoTitle")?encodeURIComponent(this.getAttribute("videoTitle")):"Play video",e.posterUrl=`https://i.ytimg.com/vi/${e.videoId}/hqdefault.jpg`,YouTubeLiteEmbed.addPrefetch("preload",e.posterUrl,"image")}connectedCallback(){const e=this.shadowRoot;this.style.backgroundImage=`url("${e.posterUrl}")`;let t=e.querySelector(".ytl");t||this.addWrapper(),(t=e.ytl).heading||this.addHeading(),t.querySelector(".lty-playbtn")||this.addButton(),t.addEventListener("pointerover",YouTubeLiteEmbed.warmConnections,{once:!0}),t.playBtn.addEventListener("click",e=>{t.classList.add("-js-loading"),this.addIframe()})}static addPrefetch(e,t,o){const d=document.createElement("link");d.rel=e,d.href=t,o&&(d.as=o),d.crossorigin=!0,document.head.append(d)}static warmConnections(){YouTubeLiteEmbed.preconnected||(YouTubeLiteEmbed.addPrefetch("preconnect","https://www.youtube-nocookie.com"),YouTubeLiteEmbed.addPrefetch("preconnect","https://www.google.com"),YouTubeLiteEmbed.addPrefetch("preconnect","https://googleads.g.doubleclick.net"),YouTubeLiteEmbed.addPrefetch("preconnect","https://static.doubleclick.net"),YouTubeLiteEmbed.preconnected=!0)}addWrapper(){const e=this.shadowRoot,t=document.createElement("div");t.className="ytl",e.appendChild(t),e.ytl=t}addHeading(){const e=this.shadowRoot,t=document.createElement("h3");t.id=decodeURIComponent(e.videoId),t.className="ytl_title",t.textContent=decodeURIComponent(e.heading),e.ytl.heading=t,e.ytl.appendChild(t)}addButton(){const e=this.shadowRoot,t=document.createElement("button");t.type="button",t.classList.add("ytl_btn-play"),t.setAttribute("aria-label","Play video: "+decodeURIComponent(e.heading)),t.setAttribute("aria-pressed",!1),t.innerHTML='\n<svg class=ytl_svg viewBox="0 0 68 48" aria-hidden=true focusable=false><g class=ytl_path-play><path class=ytl_path-playBg d="M66.52,7.74c-0.78-2.93-2.49-5.41-5.42-6.19C55.79,.13,34,0,34,0S12.21,.13,6.9,1.55 C3.97,2.33,2.27,4.81,1.48,7.74C0.06,13.05,0,24,0,24s0.06,10.95,1.48,16.26c0.78,2.93,2.49,5.41,5.42,6.19 C12.21,47.87,34,48,34,48s21.79-0.13,27.1-1.55c2.93-0.78,4.64-3.26,5.42-6.19C67.94,34.95,68,24,68,24S67.94,13.05,66.52,7.74z"/><path d="M 45,24 27,14 27,34" fill=#fff /></g><circle class=ytl_path-loading cx=34 cy=24 r=18 fill=none stroke=#fff stroke-dasharray="60 30" stroke-width=4 transform="rotate(190 34 24)"/></svg>',e.ytl.playBtn=t,e.ytl.appendChild(t)}addIframe(){const e=this.shadowRoot,t=`\n<iframe class=ytl_iframe title="${decodeURIComponent(e.heading)}" frameborder=0 allowfullscreen allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"\nsrc="https://www.youtube-nocookie.com/embed/${e.videoId}?autoplay=1"></iframe>`;e.ytl.insertAdjacentHTML("beforeend",t);const o=e.querySelector(".ytl_iframe");o.addEventListener("load",t=>{setTimeout(t=>{e.ytl.classList.add("-js-loaded")},1e3)},{once:!0}),o.focus()}}
customElements.define('yt-l', YouTubeLiteEmbed);
</code></pre>
</figure>
</section>
<section>
<h2>Alternative solutions</h2>
<p class=tagline>This is Version 3 which is heavily based on the Paul Irish project: <a class=-nowrap target=_blank title="[new window]" href="https://github.com/paulirish/lite-youtube-embed">Lite YouTube Embed</a>, but updated to meet WCAG Accessibility requirements.</p>
<p>There's also a pen of <a target=_blank title="[new window]" href="https://codepen.io/2kool2/pen/dyoJrav">Version 2</a> which was loosely based around <a target=_blank title="[new window]" href="https://www.cssscript.com/load-youtube-video-thumbnail-lazytube/">LazyTube</a> and doesn't use Custom Elements.</p>
<p>Another method worthy of serious consideration is: <a class=-nowrap target=_blank title="[new window]" href="https://dev.to/haggen/lazy-load-embedded-youtube-videos-520g">Lazy load embedded YouTube videos</a> by Arthur Corenzan.</p>
<p>Personally, if you can get away from YouTube as a hosting solution, I prefer <a target=_blank title="[new window]" href="https://codepen.io/2kool2/pen/WNvywpB?editors=1000">Cloud CDN-hosted video</a> using <a class=-nowrap target=_blank title="[new window]" href="https://cloudinary.com/">Cloudinary</a> or <a class=-nowrap target=_blank title="[new window]" href="https://www.netlify.com/">Netlify</a> and the HTML video element. Far less data transferred, and easier to embed.</p>
<h2>Credits</h2>
<p>Videos courtesy of <a class=-nowrap target=_blank title="[new window]" href="http://batthedog.uk/">Bat the Dog</a></p>
<p>Font-size, and spacing, calculation generated by: <a class=-nowrap target=_blank title="[new window]" href="https://websemantics.uk/tools/responsive-font-calculator/">Fluid-responsive font-size calculator</a></p>
<p>Code blocks: <a class=-nowrap target=_blank title="[new window]" href="https://codepen.io/2kool2/pen/MEbeEg">Code highlighting with Prism.js</a></p>
<p>Embedding code: <a class=-nowrap target=_blank title="[new window]" href="https://websemantics.uk/tools/escaping-html/">Escaping HTML symbols/entities</a></p>
</section>
</main>
<!-- Codepen footer include -->
[[[https://codepen.io/2kool2/pen/mKeeGM]]]
/* Generic page styles */
:root {
/* Fluidly variable between: 16px @ 320px and 32px @ 1920px */
--space: calc(1rem + ((1vw - 0.2em) * 1));
--spaceDouble: calc(var(--space) * 2);
--spaceTwoThirds: calc(var(--space) / 1.5);
--spaceHalf: calc(var(--space) / 2);
--spaceThird: calc(var(--space) / 3);
--spaceQuarter: calc(var(--space) / 4);
--maxTextWidth: 35em;
--colorF: #f5f5f5;
--colorE: #e5e5e5;
--colorD: #d5d5d5;
--bgColor0: #0a0a0a;
--bgColor1: #1a1a1a;
--bgColor2: #2a2a2a;
font-size: var(--space);
line-height: 1.7;
max-width: 120rem;
margin: 0 auto;
}
@media (min-width: 120em) {
:root {
--space: 2rem;
}
}
body {
color: var(--colorD);
background-color: var(--bgColor0);
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Cdefs%3E%3Cfilter id='a'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.7'/%3E%3C/filter%3E%3C/defs%3E%3Crect filter='url(%23a)' opacity='.3' width='100%25' height='100%25'/%3E%3C/svg%3E");
background-attachment: fixed;
margin: var(--space);
font-family: sans-serif;
}
h1 {
font-size: 1.5rem;
font-weight: 100;
line-height: 1.2;
margin: 0 0 var(--spaceHalf);
}
h2 {
font-size: 1.25rem;
font-weight: 100;
line-height: 1.2;
margin: var(--spaceDouble) 0 0;
}
h2 > span {font-size:smaller}
h3 {
font-size: 1rem;
font-weight: 100;
line-height: 1.2;
}
section {
max-width: var(--maxTextWidth);
margin-left: auto;
margin-right: auto;
}
.-fullWidthBlock {
max-width: none;
}
p, ul {margin: var(--spaceTwoThirds) 0 0}
li {margin: var(--spaceQuarter) 0 0}
p, li {
font-weight: 100;
}
.-nowrap {white-space:nowrap}
/* Fancier text links */
body {
--fancyColor: hsla(214,72%,48%,1);
--fancyColorHover: hsla(214,72%,20%,1);
--fancyBgHover: hsla(214,100%,80%,1);
--fancyUnderline: hsla(214,72%,48%,1);
}
@media (prefers-color-scheme: dark) {
body:not([data-lightMode="light"]) {
--fancyColor: hsla(214,100%,72%,1);
--fancyColorHover: #fff;
--fancyBgHover: hsla(214,100%,25%,1);
--fancyUnderline: hsla(214,100%,72%,.4);
}
}
body[data-lightMode="dark"] {
--fancyColor: hsla(214,100%,72%,1);
--fancyColorHover: #fff;
--fancyBgHover: hsla(214,100%,25%,1);
--fancyUnderline: hsla(214,100%,72%,.4);
}
/* Fancy links */
a:link,
a:visited {
color: var(--fancyColor);
white-space: nowrap;
position: relative;
text-decoration: none;
border-bottom: 1px solid var(--fancyUnderline);
transition: color .3s ease-out;
}
a:hover,
a:focus {
color: var(--fancyColorHover);
}
a::before,
a::after {
content: '';
position: absolute;
left: 0;
width: 100%;
opacity: .5;
transform: scaleX(0);
transition: all .2s;
}
a::before {
background-color: var(--fancyBgHover);
outline-offset: -.25rem;
outline: var(--fancyBgHover) solid .5rem;
height: 100%;
bottom: 0;
z-index: -1;
}
a::after {
background-color: var(--fancyColor);
bottom: -0.1rem;
height: 0.1rem;
}
a:hover::before,
a:focus::before,
a:hover::after,
a:focus::after {
opacity: 1;
transform: scaleX(1);
}
/* Grid layout */
.video_lst {
--columns: 1fr;
display: grid;
grid-gap: var(--space);
grid-template-columns: var(--columns);
list-style: none;
margin: var(--spaceHalf) 0 0;
padding: 0;
}
@media(min-width: 50em) { /* 800px */
.video_lst {
--columns: 1fr 1fr;
}
}
/* Video Players */
[class^="vdo-"] {
background-color: #000;
background-position: center center;
background-size: cover;
transition: box-shadow .3s ease-out;
}
/* I prefer interactive content to "come forwards" on hover or focus - hence the drop-shadow */
[class^="vdo-"]:hover,
[class^="vdo-"]:focus-within {
box-shadow: 0 .25rem .25rem hsla(0,0%,0%,0.5);
}
.vdo-1 {
margin: var(--spaceTwoThirds) 0 0;
}
/* The component / module */
yt-l {
opacity:0;
transition: opacity 3s ease-out 1s;
/* Exposed "globally-scoped" custom properties: */
/* These are the default values */
/* May be overwritten, but do not require defining here */
--aspectRatio: calc(100% / (16 / 9));
--overlayBgImg: linear-gradient(0,
rgba(0,0,0,.4) 6%,
rgba(0,0,0,0) 50%,
rgba(0,0,0,.4) 100%
);
--btnHeight: 3rem;
--titleColor: #fff;
--titleBgColor: #000;
--titleFont: 1rem/1 sans-serif;
--titlePadding: .25rem;
/* Default overrides */
--titleFont: var(--space)/1.3 sans-serif;
--titlePadding: var(--spaceQuarter);
}
@media(min-width: 50em) {
yt-l.vdo-2 {
/* Adjustments for two columns */
--btnHeight: calc(var(--space) * 1.75);
--titleFont: var(--spaceTwoThirds)/1.3 sans-serif;
}
}
/* Code containers */
figure {
max-width: var(--maxTextWidth);
margin: var(--spaceDouble) 0;
}
/* Includes Prism code highlighting: https://codepen.io/2kool2/pen/MEbeEg */
// Force dark mode for links and code highlighting
document.body.setAttribute('data-lightMode', 'dark');
const template = document.createElement('template');
template.innerHTML = `
<style>
:host {
--aspectRatio: calc(100% / (16 / 9));
--overlayBgImg: linear-gradient(0, rgba(0,0,0,.4) 6%, rgba(0,0,0,0) 50%, rgba(0,0,0,.4) 100%);
--btnHeight: 3rem;
--titleColor: #fff;
--titleBgColor: #000;
--titleFont: 1rem/1 sans-serif;
--titlePadding: .25rem;
display: block;
position: relative;
contain: content;
cursor: pointer;
}
.ytl::before {
content: '';
position: absolute;
width: 100%;
height: 100%;
background-image: var(--overlayBgImg);
transition: opacity 0.3s ease-out;
}
/* Lose the bgImg shadow on hover / focus */
.ytl:focus-within::before,
.ytl:hover::before {
opacity: 0;
}
.ytl::after {
content: "";
display: block;
padding-bottom: var(--aspectRatio);
}
.ytl_btn-play::-moz-focus-inner {
border: 0;
}
/* Button is the full size of video player */
.ytl_btn-play {
display: block;
position: absolute;
width: 100%;
height: 100%;
background-color: transparent;
border: none;
padding: 0;
cursor: pointer;
}
/* The SVG is centered to the button */
.ytl_svg {
display: block;
position: absolute;
top: 50%;
left: 50%;
width: calc(var(--btnHeight) * 1.42);
height: var(--btnHeight);
transform-origin: 50% 50%;
z-index: 1;
transform: translate3d(-50%, -50%, 0);
}
/* Add color on hover / focus */
.ytl_path-playBg {
fill: hsla(0,0%,0%,.5);
transition: fill .3s ease-out;
}
.ytl_path-playBg + path {
fill: #fff;
}
.ytl_btn-play:hover .ytl_path-playBg,
.ytl_btn-play:focus .ytl_path-playBg {
fill: hsla(0,100%,50%,1);
outline: none;
}
.ytl_title {
position: absolute;
bottom: 0;
width: 100%;
color: var(--titleColor);
background-color: var(--titleBgColor);
font: var(--titleFont);
text-align: center;
margin: 0;
padding: var(--titlePadding);
transition: opacity .3s ease-out, visibility 0s ease-out .3s;
}
.ytl_iframe {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
opacity: 0;
transition: opacity 1s ease-out;
}
/* Iframe loading - Switch button svg from play to spinner */
.-js-loading .ytl_svg {
transform: translate3d(-50%, -50%, 0) scale(1.6);
opacity: .7;
}
.ytl_path-loading {
display: none;
transform-origin: 50% 50%;
animation: rotating 1s linear infinite;
}
.-js-loading .ytl_path-loading {
display: block;
}
.-js-loading .ytl_path-play {
display: none;
}
@keyframes rotating {
from {transform: rotate(0deg)}
to {transform: rotate(359deg)}
}
/* Iframe loaded - Fade in iframe and remove button and bg gradient */
.-js-loaded {
cursor: unset;
}
.-js-loaded > .ytl_iframe {
opacity: 1;
}
/* Remove from keychain by removing visibility */
.-js-loaded::before,
.-js-loaded > .ytl_title,
.-js-loaded > .ytl_btn-play {
visibility: hidden;
opacity: 0;
}
</style>`;
class YouTubeLiteEmbed extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
const tsr = this.shadowRoot;
tsr.appendChild(template.content.cloneNode(true));
tsr.videoId = encodeURIComponent(this.getAttribute('videoid'));
tsr.heading = this.getAttribute('videoTitle') ? encodeURIComponent(this.getAttribute('videoTitle')) : 'Play video';
tsr.posterUrl = `https://i.ytimg.com/vi/${tsr.videoId}/hqdefault.jpg`;
YouTubeLiteEmbed.addPrefetch('preload', tsr.posterUrl, 'image');
tsr.host.style.opacity = 1;
// Or let a late-loader handle the poster image loading (my personal preference)
// this.setAttribute('data-LL-src', tsr.posterUrl);
}
connectedCallback() {
const tsr = this.shadowRoot;
// If late-loading the poster, remove this line
this.style.backgroundImage = `url("${tsr.posterUrl}")`;
let ytl = tsr.querySelector('.ytl');
if (!ytl) this.addWrapper();
ytl = tsr.ytl;
if (!ytl.heading) this.addHeading();
let playBtn = ytl.querySelector('.ytl_btn-play');
if (!playBtn) this.addButton();
ytl.addEventListener('pointerover',
YouTubeLiteEmbed.warmConnections, {once: true});
ytl.playBtn.addEventListener('click', e => {
ytl.classList.add('-js-loading');
this.addIframe();
});
}
static addPrefetch(kind, url, as) {
const linkElem = document.createElement('link');
linkElem.rel = kind;
linkElem.href = url;
if (as) linkElem.as = as;
linkElem.crossorigin = true;
document.head.append(linkElem);
}
static warmConnections() {
if (YouTubeLiteEmbed.preconnected) return;
YouTubeLiteEmbed.addPrefetch('preconnect', 'https://www.youtube-nocookie.com');
YouTubeLiteEmbed.addPrefetch('preconnect', 'https://www.google.com');
YouTubeLiteEmbed.addPrefetch('preconnect', 'https://googleads.g.doubleclick.net');
YouTubeLiteEmbed.addPrefetch('preconnect', 'https://static.doubleclick.net');
YouTubeLiteEmbed.preconnected = true;
}
addWrapper() {
const tsr = this.shadowRoot;
const ytl = document.createElement('div');
ytl.className = 'ytl';
tsr.appendChild(ytl);
tsr.ytl = ytl;
}
addHeading() {
const tsr = this.shadowRoot;
const heading = document.createElement('h3');
heading.id = decodeURIComponent(tsr.videoId);
heading.className = 'ytl_title';
heading.textContent = decodeURIComponent(tsr.heading);
tsr.ytl.heading = heading;
tsr.ytl.appendChild(heading);
}
createSVG() {
}
addButton() {
const tsr = this.shadowRoot;
const playBtn = document.createElement('button');
playBtn.type = 'button';
playBtn.classList.add('ytl_btn-play');
playBtn.setAttribute('aria-label', 'Play video: ' + decodeURIComponent(tsr.heading));
playBtn.setAttribute('aria-pressed', false);
playBtn.innerHTML = `
<svg class=ytl_svg viewBox="0 0 68 48" aria-hidden=true focusable=false>
<g class=ytl_path-play>
<path fill=none class=ytl_path-playBg d="M66.52,7.74c-0.78-2.93-2.49-5.41-5.42-6.19C55.79,.13,34,0,34,0S12.21,.13,6.9,1.55 C3.97,2.33,2.27,4.81,1.48,7.74C0.06,13.05,0,24,0,24s0.06,10.95,1.48,16.26c0.78,2.93,2.49,5.41,5.42,6.19 C12.21,47.87,34,48,34,48s21.79-0.13,27.1-1.55c2.93-0.78,4.64-3.26,5.42-6.19C67.94,34.95,68,24,68,24S67.94,13.05,66.52,7.74z"/>
<path d="M 45,24 27,14 27,34" fill=none />
</g>
<circle class=ytl_path-loading cx=34 cy=24 r=18 fill=none stroke=#fff stroke-dasharray="60 30" stroke-width=4 transform="rotate(190 34 24)"/>
</svg>
`;
tsr.ytl.playBtn = playBtn;
tsr.ytl.appendChild(playBtn);
}
addIframe() {
const tsr = this.shadowRoot;
// WCAG - iframes require a title
const iframeHTML = `
<iframe class=ytl_iframe title="${decodeURIComponent(tsr.heading)}" frameborder=0 allowfullscreen allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
src="https://www.youtube-nocookie.com/embed/${tsr.videoId}?autoplay=1"></iframe>`;
tsr.ytl.insertAdjacentHTML('beforeend', iframeHTML);
const iframe = tsr.querySelector('.ytl_iframe');
iframe.addEventListener('load', e => {
// Wait 1 second for video to start running before fading it in
// Allows for a smoother transition betwen static image and video.
// Alternatively you could load the API for the playerready event but it defeats the purpose.
setTimeout(_ => {
tsr.ytl.classList.add('-js-loaded');
}, 1000);
}, {once: true});
iframe.focus();
}
}
customElements.define('yt-l', YouTubeLiteEmbed);
/* Includes Prism code highlighting: https://codepen.io/2kool2/pen/MEbeEg */
Also see: Tab Triggers