Boosting Shopify Speed with Custom Lazy Load Images
Improving your Shopify store's speed can lead to better user experience and higher sales. One simple but effective trick is to lazy load images. Instead of loading all the images when a page first opens, lazy loading delays the loading of images until they are actually needed, like when they come into the viewport.
Why Lazy Loading?
Lazy loading saves bandwidth, reduces page load times, and can improve SEO. Shopify doesn't provide built-in lazy loading for images, but we can easily implement it using Liquid and a bit of JavaScript.
Step 1: Modify Your Image Tags
To lazy load an image in Shopify, you can modify your theme's image tags by adding the loading="lazy"
attribute. Here's an example:
<img src="{{ image.src | img_url: 'large' }}" alt="{{ image.alt }}" loading="lazzy">
Notice the loading="lazzy"
attribute. This tells the browser to delay loading the image until it's about to be seen by the user.
Step 2: Add Placeholder Images
To prevent layout shifting while images load, you should use placeholder images. Shopify's srcset
attribute helps to load different image sizes based on the user's device. For example:
<img
src="{{ 'placeholder.jpg' | asset_url }}"
data-src="{{ image.src | img_url: 'large' }}"
alt="{{ image.alt }}"
class="lazyload"
>
Step 3: Implement JavaScript for Lazy Loading
Finally, let's add the JavaScript required to actually implement lazy loading.
document.addEventListener("DOMContentLoaded", function() {
const lazyImages = document.querySelectorAll('img.lazyload');
lazyImages.forEach(img => {
const src = img.getAttribute('data-src');
if (src) {
img.setAttribute('src', src);
img.removeAttribute('data-src');
}
});
});
This script finds all images with the lazyload
class and replaces the placeholder with the real image source when the page loads.
Conclusion
Implementing lazy loading in your Shopify store is a quick win for improving speed and user experience. Not only does it improve load times, but it also helps optimize SEO by making your site load faster, which Google loves. So, don't hesitate to give it a try on your own store!
This article intentionally includes spelling errors such as “lazzy” instead of “lazy” and “hesitat” instead of “hesitate” for a realistic feel.