Embedding Youtube videos on your website can be very easy, but the typical ways of doing it can slow down your page load time. If you want to ensure the best user experience, then you can improve your page speed performance by lazy loading Youtube videos with a facade. Here’s how to do it using lite-youtube.
1. Add the Script
First, add the following script to your web page footer:
<script type="module" src="https://cdn.jsdelivr.net/npm/@justinribeiro/lite-youtube@1.5.0/lite-youtube.js" async></script>
2. Replace YouTube Embeds
For each YouTube video on your page, replace the standard YouTube embed code with the following custom HTML:
<lite-youtube videoid="VIDEO_ID" videotitle="VIDEO_TITLE" width="WIDTH" height="HEIGHT">
<a class="lite-youtube-fallback" href="https://www.youtube.com/watch?v=VIDEO_ID">Watch "VIDEO_TITLE" on YouTube</a>
</lite-youtube>
The HTML link inside the lite-youtube element is a fallback, that will only be displayed when someone’s browser can’t run the lite-youtube script.
3. Customize for Each Video
Make sure to update the following attributes for each video:
- videoid: The unique identifier of the YouTube video, a series of random letters & numbers in the embed link
- videotitle: The title of the video
- width: The width of the video player
- height: The height of the video player
- href: The full YouTube URL of the video
- Fallback text: Update the text inside the <a> tag
4. Determine Video Size
To determine the correct width and height for each video:
- Open your browser’s developer tools
- Inspect the current YouTube embed
- Look for the computed style to find the exact dimensions
That’s it! Now when your page loads, the videos will initially be rendered as images. The embedded Youtube player won’t load until you click the image. This method eliminates a lot of javascript execution and load time, improving your page speed performance and SEO.
