Whenever you embed a youTube video on a site, the page load takes a significant amount of time and makes a lot of requests. I wanted to avoid that. I found that the video iframe can be loaded on demand.
Why?
Youtube iframe loads a lot of things which takes time and resources. What if we can circumbent that.
Not all videos you embed on a website are watched by your users
Even after the embed, users usually see a thumbnail with play button which we can provide manually.
YouTube Thumbnail URL
Getting youtube thumbnail is easy if you have the video ID. This can also be done through YouTube API but it is an overkill for what we want to achieve here.
https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
Refer this answer
I just add a play button over this image and on click I will replace the image with iframe.
Youtube.svelte
<script>
let play = false;
</script>
{#if play}
<iframe src="https://www.youtube.com/embed/q2Y3f0lHnMs"></iframe>
{:else}
<img src="https://img.youtube.com/vi/q2Y3f0lHnMs/maxresdefault.jpg" />
{/if}
The image loads faster on subsequent page load because it is cached by the browser!