Sprocket Rocket
  • Sprocket Rocket Design System
  • Initial Setup
    • Setup HubL Local Server
    • Setup SR App Locally
    • Clone LaunchPad Starter
  • Create a New Module
    • Design
    • Code
    • Implementation
    • Create a Pull Request
    • Fields JSON
  • Code Patterns
    • Design Settings
    • Headings
    • Responsive Images
    • Implementing Forms
    • Typography
    • CTA/Button
    • Spacers
  • PR Review
    • Design / Code Review
    • Implementation Review
  • Handoff Relay Checklist
    • Client Request - Handoff
    • Page/Template Design - Handoff
    • Module Design - Handoff
    • Page/Template Development - Handoff
    • Module Development - Handoff
    • Review & Delivery - Handoff
  • Guides and Tutorials
    • Code Snippets
    • Lazy Loading
    • How to setup the blog subscription notification emails
    • 404 Error Tracking Event with Google Analytics and Google Tag Manager
    • How to setup a form to be used with SR Conversational Form 01
    • Upgrading Bootstrap to Latest Version
  • HS Page Launch (QC)
  • SR Agency Website Review Checklist (QC)
Powered by GitBook
On this page
  1. Guides and Tutorials

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);
PreviousCode SnippetsNextHow to setup the blog subscription notification emails

Last updated 4 years ago