Image Instead of YouTube iFrame for Faster Page Load Times?

IlluminateLabs
Excursionist
95 0 7

I've been reading about this strategy being used on custom and Wordpress sites but haven't seen any tutorials for Shopify. It seems like a clever solution.

Basically YouTube embeds drastically reduce page load speeds, especially on mobile. Since we use them on many of our pages this is an issue.

Is there a way to set a screenshot image with a play button in the place of the YouTube embed on Shopify, and only load the actual YouTube video when the user clicks it?

0 Likes
ThemuMitch
Explorer
45 11 11

What you're after here is deferring the loading of the YouTube embeds until after the page has loaded. The simplest way to achieve this would be doing as follows:

 

1) Edit all embeds on each page of your store

You want to remove the src attribute of each <iframe> referencing YouTube and replace it with a data-* attribute (in this example, I've used data-src). This will improve page load times, as the page won't be requesting video resources from YouTube before loading. For example, change:

<iframe src="https://www.youtube.com/embed/neFK-pv2sKY"></iframe>

... to:

<iframe data-src="https://www.youtube.com/embed/neFK-pv2sKY"></iframe>

 

2) Add JavaScript to theme.js

Upon page load (when the user can interact with the page), we want to add the src attribute back into the <iframe> elements. After doing so, the <iframe> elements will automatically request video resources from YouTube and become usable after a short time. For example, add this code to the bottom of the theme.js file:

window.onload = function() {
  for (let iframe of document.querySelectorAll('[data-src]')) {
    iframe.setAttribute('src', iframe.getAttribute('data-src'));
  }
}

 

Note that this is untested and I can't guarantee this approach will work for all Shopify themes, but it should give you an idea of where to start.

 

I hope this helps.

Was your problem solved? Please mark this post as an Accepted Solution
0 Likes
IlluminateLabs
Excursionist
95 0 7

@ThemuMitch Hey I appreciate your feedback. I just tried this, and while it seemed to reduce first contentful paint time a bit, it increased largest contentful paint a bit also.

This may be a good way to get the page rendering faster, but it doesn't seem like a solution for getting the entire page loading faster. Largest contentful paint is a core web vital which we score very poorly for and that's why I feel like the image-swap solution is probably the only long-term solution. But I'm just beginning to explore this and definitely not an expert.

0 Likes