Defer loading a Youtube video on Shopify (and other CMS)

Summary

In a previous article, we saw how it was better tohost their videos directly on their site.

If you prefer all the same directly integrate a Youtube video, you must be aware that this will slow down your site and lower your speed score on Shopify, Pagespeed or even GTmetrix.

The solution to this problem is to add the function lazy loading to your video.

What is lazy loading?

Lazy loading is the principle of only loading what you see on the screen. Anything outside remains on hold, and will charge when we get to it.

Lazy loading example

Integrate lazy loading into a Youtube video

For this integration, we will use the script vanilla LazyLoad. It is a very light script (less than 2,4 KB) which allows you to add the lazy loading function to your website and therefore to delay the loading of your images, videos and iframes (which interests us here) below the waterline until they come into action.

Waterline

To do this, we add the following script before the tag in the theme.liquid of our Shopify theme :

<script async="" src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@latest/dist/lazyload.min.js"></script>

Note: Don't forget to save your theme before modifying it. Or use our app GoBack to save your theme automatically.

Then all that remains is to modify the iframe of our Youtube video.

When looking to embed a Youtube video, from Youtube, you receive the following HTML element:

<iframe width="560" height="315" src="https://www.youtube.com/embed/XXXXXXX" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

To apply our Vanilla script, all you have to do is,

Change src = to data-src =: 

<iframe width="560" height="315" data-src="https://www.youtube.com/embed/XXXXXXX" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Embed a script before the tag de theme.liquid :

<script>
window.lazyLoadOptions = {
};
window.addEventListener("LazyLoad::Initialized", function (event) {
    window.lazyLoadInstance = event.detail.instance;
}, false);
</script> 

And it's over!

Leave a comment

Please note that comments must be approved before posting