85% faster YouTube embeds with iframe srcdoc!
swyx
TLDR
The Problem
When I ran a PageSpeed Insights test on https://www.swyx.io/new-mac-setup-2021 I was surprised to find really poor performance:
screenshot
This was an obvious result of me loading the YouTube embed by YouTube’s recommended method:
<iframe id="player" type="text/html" width="640" height="390"
src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com"
frameborder="0"></iframe>
This loads some JavaScript eagerly that is unused during first render, which is obviously inefficient.
The Solution
It turns out you can massively improve load times and lighthouse scores by moving the src
embed into srcdoc
(StackOverflow answer) and requiring an extra click to load the JS:
This one change (diff) causes much better performance.
screenshot
The new embed code is here:
<style>
body, .youtubeembed {
width: 100%;
height: 100%;
margin: 0;
position: absolute;
display: flex;
justify-content: center;
object-fit: cover;
}
</style>
<a
href='https://www.youtube.com/embed/${videoId}?autoplay=1'
class='youtubeembed'
>
<img
src='https://img.youtube.com/vi/${videoId}/sddefault.jpg'
class='youtubeembed'
/>
<svg
version='1.1'
viewBox='0 0 68 48'
width='68px'
style='position: relative;'
>
<path 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' fill='#f00'></path>
<path d='M 45,24 27,14 27,34' fill='#fff'></path>
</svg>
</a>
This works without JavaScript; if you use a framework it’s up to you to figure out how to adapt it to your framework.
- This reader adapted it to work with Hugo!
Alternative
I haven’t tried this yet but probably should - https://github.com/paulirish/lite-youtube-embed I just have a wariness around web components and dont know the JS overhead.