Lazy Loading Youtube Embeds
After images the biggest payloads in my pages are Youtube embedded videos and since I already lazy load images I've decided to explore how to best lazy load embedded Youtube iframes; I embed Vimeo videos far less often so I'm not going to lazy load them. I have the following requirements for any lazy loading solution: - The video must be responsive - Any external script, stylesheets and assets must be less than 5kb in size ## The original This is what I normally do when working with video on the web and in my Wordpress blogs. I take the `iframe` element directly from Youtube and wrap it around a div with a class of `video` to style it accordingly ```markup
';
let play = '';
return thumb.replace("ID", id) + play;
};
```
`loadIframe` builds the iframe element and populates it with the video we want, again by referencing its ID. It also provides attributes to control the frame around the video and whether we can go full screen with it.
```javascript
function loadIframe() {
let iframe = document.createElement("iframe");
let embed = "https://www.youtube.com/embed/ID?autoplay=1&rel=0";
iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "1");
this.parentNode.replaceChild(iframe, this);
}
```
Finally, we use CSS to style the video and programmatically add the play button. as an overlay.
```css
.youtube-player {
position: relative;
padding-bottom: 56.23%;
/* Use 75% for 4:3 videos */
height: 0;
overflow: hidden;
max-width: 100%;
background: #000;
margin: 5px;
}
.youtube-player iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 100;
background: transparent;
}
.youtube-player img {
bottom: 0;
display: block;
left: 0;
margin: auto;
max-width: 100%;
width: 100%;
position: absolute;
right: 0;
top: 0;
border: none;
height: auto;
cursor: pointer;
-webkit-transition: .4s all;
-moz-transition: .4s all;
transition: .4s all;
}
.youtube-player img:hover {
-webkit-filter: brightness(75%);
}
.youtube-player .play {
height: 72px;
width: 72px;
left: 50%;
top: 50%;
margin-left: -36px;
margin-top: -36px;
position: absolute;
background: url("../images/play.png") no-repeat;
cursor: pointer;
}
```
## What's next?
This is the kind of project that would benefit greatly from ES6's Template Literals or maybe even building a custom element for this. I may also want to turn this into a Wordpress function for my blogs.