Reputation: 309
I have a page with 3 (possibly more in the future) embedded youtube videos. I've heard that lazy loading these components is a good way to decrease the number of HTTP requests up top, have less content unnecessarily downloaded and have a faster page load.
I've seen lazy loading solutions for youtube videos written in vanilla JavaScript and jQuery accessing the DOM directly, but I was wondering if there's a better 'React way' of doing it?
Any feedback would be appreciated!
Upvotes: 6
Views: 2631
Reputation: 547
Just need to add a single line of code and its lazy loaded for six videos
instead of having an attribute of src={value}, have srcdoc={``}
The trick is rooted in srcdoc, a feature of where you can put the entire contents of an HTML document in the attribute. It’s like inline styling but an inline-entire-documenting sort of thing.
{["sh0EGUheef8", "1H72tRzG5TU", "cbBB-unybLA", "lv-YIJC1xWo", "PBwslCZRnaU", "w2zQ4lMFoMg"].map((value, index) => (
<div key={index}>
<iframe
title="Youtube"
aria-hidden="true"
className={classes.iframe}
frameBorder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
webkitallowfullscreen="true"
mozallowfullscreen="true"
srcDoc={`<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto}span{height:1.5em;text-align:center;font:48px/1.5 sans-serif;color:white;text-shadow:0 0 0.5em black}</style><a href=https://www.youtube.com/embed/${value}/?autoplay=1><img src=https://img.youtube.com/vi/${value}/hqdefault.jpg alt='Video The Dark Knight Rises: What Went Wrong? – Wisecrack Edition'><span>▶</span></a>`}
></iframe>
</div>
The only problem is that the frame. The user will have to click it again. Since the first click was only to load the video. It still saves the junk that would get downloaded otherwise, and specially for mobile, those 500KB could hurt.
Upvotes: 3