← Back to aFarkas/lazysizes

How to Deploy & Use aFarkas/lazysizes

lazysizes Deployment & Usage Guide

Prerequisites

For End Users (Integration):

  • Modern web browser (Chrome, Firefox, Safari, Edge)
  • Web project with HTML/JavaScript access
  • No runtime dependencies or build tools required

For Contributors/Development:

  • Node.js (v12 or higher recommended)
  • npm or yarn package manager
  • Git

Installation

Option 1: npm/yarn (Recommended for Bundled Projects)

npm install lazysizes --save
# or
yarn add lazysizes

Import in your JavaScript (ES6 modules):

import 'lazysizes';
// Import specific plugins as needed
import 'lazysizes/plugins/parent-fit/ls.parent-fit';

Important: Never import the *.min.js files from the npm package when using bundlers.

Option 2: CDN (Simplest for Static Sites)

Add to your HTML <head>:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.2/lazysizes.min.js" async></script>

Option 3: Direct Download

Download lazysizes.min.js and include locally:

<script src="path/to/lazysizes.min.js" async></script>

Option 4: Bower (Legacy)

bower install lazysizes --save

Configuration

Basic Markup Configuration

Add the lazyload class and data-src attribute to images:

<!-- Standard image -->
<img data-src="image.jpg" class="lazyload" />

<!-- Responsive image with automatic sizes calculation -->
<img 
    data-src="image.jpg"
    data-srcset="image-small.jpg 300w, image-medium.jpg 600w, image-large.jpg 900w"
    data-sizes="auto"
    class="lazyload" />

<!-- Low-quality image placeholder (LQIP) pattern -->
<img 
    src="low-quality-placeholder.jpg"
    data-src="high-quality-image.jpg"
    class="lazyload" />

<!-- Iframe lazy loading -->
<iframe 
    class="lazyload"
    data-src="//www.youtube.com/embed/ZfV-aYdU4uE"
    frameborder="0" 
    allowfullscreen>
</iframe>

JavaScript Configuration Object

Configure via window.lazySizesConfig before the script loads:

<script>
window.lazySizesConfig = window.lazySizesConfig || {};
window.lazySizesConfig.lazyClass = 'lazyload';
window.lazySizesConfig.loadedClass = 'lazyloaded';
window.lazySizesConfig.loadingClass = 'lazyloading';
window.lazySizesConfig.expand = 300; // Preload pixels before viewport
window.lazySizesConfig.expFactor = 1.5; // Multiplier for expand on scroll
window.lazySizesConfig.loadMode = 2; // 0=none, 1=visible only, 2=visible+nearby, 3=all
</script>
<script src="lazysizes.min.js" async></script>

Available Configuration Options:

OptionDefaultDescription
lazyClass'lazyload'Class name for elements to lazy load
loadedClass'lazyloaded'Class added when loading complete
loadingClass'lazyloading'Class added while loading
preloadClass'lazypreload'Class for immediate loading
errorClass'lazyerror'Class added on load error
srcAttr'data-src'Attribute for image src
srcsetAttr'data-srcset'Attribute for responsive images
sizesAttr'data-sizes'Attribute for sizes calculation
expand300Pixels to expand viewport for preloading
expFactor1.5Viewport expansion factor
loadMode2Resource loading strategy (0-3)
minSize40Minimum dimension to consider loading
ricTimeout0RequestIdleCallback timeout
throttleDelay125Throttle delay for scroll events

Plugin Configuration

Parent-fit Plugin (for object-fit polyfill):

import 'lazysizes/plugins/parent-fit/ls.parent-fit';

Include Plugin (for conditional loading):

<div class="lazyload" data-include="path/to/content.html"></div>

Respimg Plugin (for older browsers without picture support):

import 'lazysizes/plugins/respimg/ls.respimg';

Build & Run

For development or contributing to lazysizes:

Clone Repository

git clone https://github.com/aFarkas/lazysizes.git
cd lazysizes

Install Dependencies

npm install

Build Project

# Build all versions (standard, UMD, intersection observer)
npm run build

# Development build with watchers
npm run watch

Run Tests

npm test

File Structure

  • lazysizes.js - Standard version (scroll-based detection)
  • lazysizes-umd.js - UMD module version
  • src/lazysizes-intersection.js - IntersectionObserver version (modern browsers)
  • plugins/ - Optional plugin extensions

Deployment

Production Integration Patterns

1. Async Script Loading (Recommended) Place in <head> for best performance:

<script src="lazysizes.min.js" async></script>

2. Module Bundler (Webpack/Rollup)

// Entry point or component
import 'lazysizes';
import 'lazysizes/plugins/attrchange/ls.attrchange'; // For SPAs

3. Preloading Critical Resources

<link rel="preload" href="lazysizes.min.js" as="script">
<script src="lazysizes.min.js" async></script>

4. Server-Side Rendering (SSR) Safety The library detects SSR environments automatically and returns a no-op object if document is undefined.

Platform-Specific Deployment

Static Sites (Jekyll, Hugo, Gatsby):

  • Include the CDN script in your base template
  • Use data-src attributes in your templates/markdown

Single Page Applications (React, Vue, Angular):

// In your app initialization
import 'lazysizes';

// For dynamic content updates, use attrchange plugin:
import 'lazysizes/plugins/attrchange/ls.attrchange';

WordPress/Drupal:

  • Enqueue the script in your theme's functions.php or template
  • Use a plugin or manual template edits to convert src to data-src

Content Security Policy (CSP): Allow inline data attributes (lazysizes doesn't use inline scripts, but ensure data-src attributes are permitted).

SEO Considerations

lazysizes automatically detects non-scrolling user agents (crawlers) and reveals all images instantly. No additional configuration needed for SEO. Ensure fallback src attributes are provided for maximum compatibility:

<img src="fallback.jpg" data-src="high-res.jpg" class="lazyload" />

Troubleshooting

Images Not Loading

Issue: Images remain blurred/low-quality and don't load. Solution:

  • Verify data-src attribute is present and URL is correct
  • Check that class="lazyload" is applied
  • Ensure script is loaded (check Network tab in DevTools)
  • For dynamically added content, verify the attrchange plugin is loaded for SPA frameworks

Layout Shifts (CLS)

Issue: Page content jumps as images load. Solution:

  • Set explicit width/height attributes on images or use aspect ratio boxes
  • Use the data-sizes="auto" feature with CSS width constraints
  • Add CSS placeholders:
.lazyload, .lazyloading {
    opacity: 0;
}
.lazyloaded {
    opacity: 1;
    transition: opacity 300ms;
}

Responsive Images Not Working

Issue: srcset images don't load correctly. Solution:

  • Include data-sizes="auto" for automatic sizes calculation
  • For older browsers (IE11), include the respimg plugin:
import 'lazysizes/plugins/respimg/ls.respimg';
  • Verify image URLs in data-srcset are comma-separated with width descriptors (e.g., 300w)

Intersection Observer Version Issues

Issue: Want to use the modern IntersectionObserver version. Solution: Use lazysizes-intersection.js instead of standard version:

<script src="lazysizes-intersection.js" async></script>

Note: This version requires browser support for IntersectionObserver and falls back gracefully in unsupported environments.

CSP (Content Security Policy) Errors

Issue: Refused to load the image errors in console. Solution: lazysizes modifies image attributes dynamically. Ensure your CSP allows:

  • unsafe-inline for styles (if using dynamic styling) OR
  • Use nonce-based CSP with the lazybeforeunveil event to set nonces dynamically

Performance Issues with Many Images

Issue: Slow scrolling on pages with 100+ images. Solution:

  • Adjust expFactor to reduce preloading:
window.lazySizesConfig = {
    expFactor: 1.2,  // Reduce from default 1.5
    loadMode: 1      // Load only visible images
};
  • Use ricTimeout: 100 to defer loading during user interaction

Plugin Not Loading

Issue: Plugin functionality not working (e.g., parent-fit). Solution:

  • Ensure plugin is imported after lazysizes core
  • For global script tags, ensure correct load order:
<script src="lazysizes.min.js" async></script>
<script src="lazysizes/plugins/parent-fit/ls.parent-fit.min.js" async></script>