Lazy Loading
/* HTML */
{{ var.image('src', 'width', 'alt') }}
/* Macro - goes in variables.html - */
{% macro image(src, width, alt, custom) %}
<img data-lazy="{{ resize_image_url(src, width) }}" data-lazy-2x="{{ resize_image_url(src, width*2) }}" src="{{ resize_image_url(src, '100') }}" alt="{{ alt }}" {% if custom %}{{custom}}{% endif %} style="width: {{width}}px"/>
{% endmacro %}
/* SCRIPT - goes in footer-includes.html - */
{% if widget_data.prototype_mode.value %}
<link rel="stylesheet" href="{{ get_public_template_url('/sr/css/prototype.css') }}">
<script src="{{ get_public_template_url('/sr/js/prototype.js') }}"></script>
{% else %}
{#<script src="{{ get_public_template_url('/sr/js/lazy.js') }}"></script>#}
{% endif %}
/* JS - goes in lazy.js - */
const targets = document.querySelectorAll("[data-lazy]");
const lazyLoad = (target) => {
const io = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
let img = entry.target;
let src = img.getAttribute("data-lazy");
let srcTwo = img.getAttribute("data-lazy-2x");
img.style.width = "auto";
img.setAttribute("src", `${src}`);
img.setAttribute("srcset", `${src} 1x, ${srcTwo} 2x`);
observer.disconnect();
}
});
});
io.observe(target);
};
targets.forEach(lazyLoad);
Last updated