lazysizes

repository·gh-pages·Indexed 12 days ago

https://github.com/afarkas/lazysizes

A high-performance, SEO-friendly, and self-initializing lazy loader for images, iframes, and scripts. Version 5.3.2 features responsive image support with automatic sizes attribute calculation and a suite of extensions including artdirect for CSS-driven art direction, aspectratio to prevent layout shifts, attrchange for dynamic attribute updates, bgset for responsive background images, and blur-up for low-quality image placeholders.

Tokens
24.1K
Snippets
83
Records
102
Agent score
97%

What's inside lazysizes

  1. Extend lazysizes with plugins and snippets

    gh-pages
    While lazysizes supports standard and responsive images (src, srcset, and picture) and iframes out of the box, you can extend or adjust its behavior using the scripts provided in the plugins/ directory. These scripts can be used as full extensions or as boilerplate snippets to customize the library for your specific requirements.
  2. Use the lazysizes bgset extension for responsive background images

    gh-pages

    The bgset extension allows you to define multiple background images with width descriptors (similar to img[srcset]) or use art direction via media queries (similar to <picture>). The extension automatically selects and loads the best image size for the current viewport.

    Note: This plugin is deprecated in most cases. It is often better to use the CSS object-fit property in combination with the object-fit polyfill. If you use background-size: cover|contain with data-sizes="auto", it is recommended to use the parent-fit extension to calculate the correct sizes attribute.

    <div class="lazyload" data-bgset="image-200.jpg 200w, image-300.jpg 300w, image-400.jpg 400w" data-sizes="auto"></div>
  3. Share state between multiple included modules

    gh-pages

    When an element includes multiple modules (e.g., data-include="moduleA, moduleB"), you can pass data between them using the lazyunload and lazyload lifecycle methods within your module definitions.

    1. In lazyunload: Use the data object to set data.shareState. This object is made available to other modules being loaded/unloaded.
    2. In lazyload: Access data.shareState to retrieve the values passed from other modules.

    This allows modules to synchronize UI states, such as form input values, during the transition.

    define(function(){
    	var Nav = function(element, options) {};
    
    	Nav.prototype = {};
    
    	// Called when the module is being unloaded/replaced
    	Nav.prototype.lazyunload = function(data){
    	    data.resetHTML = true;
    	    // Share state with other modules
    	    data.shareState = {
    	        searchValue: $('input.search', data.target).val()
    	    };
    	};
    
    	// Called when the module is loaded
    	Nav.prototype.lazyload = function(data){
    	    // Check if shared state exists from another module
    	    if(data.shareState){
    	        $('input.search', data.target).val(data.shareState.searchValue || '');
    	    }
    	};
    
    	return Nav;
    });
  4. Use the <picture> element for art direction

    gh-pages

    The plugin supports the <picture> element for art direction.

    Constraints for <picture> usage:

    • The <img> element should not have a srcset or data-srcset attribute.
    • Instead, the last <source> element should be used without a media and type attribute to provide the fallback.
    • source[media] is supported in browsers that support matchMedia. For legacy support (like IE9), use a window.matchMedia polyfill.
    • source[type] is not supported automatically; you must manually enable it by overriding the lazySizesConfig.supportsType option callback.
    <picture>
        <source
            data-srcset="http://placehold.it/500x600/11e87f/fff"
            media="--small" />
        <source
            data-srcset="http://placehold.it/700x300"
            media="--medium" />
        <source
            data-srcset="http://placehold.it/1400x600/e8117f/fff"
            media="--large" />
        <source
            data-srcset="http://placehold.it/1800x900/117fe8/fff" />
        <img
            src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
            class="lazyload"
            alt="image with artdirection" />
    </picture>
  5. Use CSS classes for unveil effects

    gh-pages

    lazysizes automatically manages CSS classes to track the loading state of elements. You can use these classes to create fade-in or blur-up animations.

    • lazyloading: Added to the element as soon as loading starts.
    • lazyloaded: Added to the element as soon as the image is fully loaded or comes into view.
    • lazyload: The initial marker class.
    /* Example: Fade in image after load */
    .lazyload, .lazyloading {
      opacity: 0;
    }
    .lazyloaded {
      opacity: 1;
      transition: opacity 300ms;
    }
  6. Automatically calculate the `sizes` attribute

    gh-pages

    lazysizes can automatically calculate the sizes attribute for responsive images by setting data-sizes="auto". This feature is most effective when used with data-srcset and width descriptors (e.g., 300w).

    Example:

    <img
        data-sizes="auto"
        data-src="image2.jpg"
        data-srcset="image1.jpg 300w,
        image2.jpg 600w,
        image3.jpg 900w" class="lazyload" />

    Important Implementation Details:

    • Width Calculation: The calculation uses the display width of the image. The width must be calculable (approximately) before the image loads. Avoid width: auto on the image; instead, use a rule like img[data-sizes="auto"] { display: block; width: 100%; }.
    • Minimum Size: If the calculated width is below 40 (configurable via minSize), lazysizes traverses up the DOM tree to find a parent with a width over 40.
    • Customization: You can modify the auto-calculated width using the lazybeforesizes event.
    • Container Fitting: If you need to fit an image to a parent container (including height-based fitting or object-fit), use the parent-fit plugin.
  7. Responsive image support with picture and srcset

    gh-pages

    lazysizes supports the standard responsive image syntax (picture and srcset). For full cross-browser support, you should use a polyfill or a specific plugin:

    • picturefill: A full polyfill.
    • respimg polyfill plugin: An extremely lightweight partial polyfill.
    • responsive image on demand plugin (rias): Another plugin option.
    • Fallback: Alternatively, you can simply define a fallback src via the data-src attribute.
  8. Use the aspectratio extension to pre-occupy image space

    gh-pages

    The aspectratio plugin for lazysizes helps prevent layout shifts by calculating the required space for an image before it loads. It calculates the height based on the width (or vice versa), provided the dimensions are calculable.

    This is particularly useful for art-directed images where different source sets have different aspect ratios.

    Note: This plugin removes the data-aspectratio attribute from the element after processing. It may conflict with other plugins that rely on this specific attribute.

  9. Use the attrchange extension to handle dynamic attribute changes

    gh-pages

    The attrchange extension is used when you dynamically change data-src or data-srcset attributes on elements that have already been processed by lazysizes. Normally, you would have to manually re-add the lazyload class to these elements to trigger a reload. This extension automates that process by detecting changes to data-* attributes and adding the necessary class for you. This is particularly useful when working with reactive frameworks like React, Angular, or Ember.

    Note: If you are using React, you may also consider using the react-lazysizes module as an alternative.

    // never try to import *.min.js files 
    import lazySizes from 'lazysizes';
    import 'lazysizes/plugins/attrchange/ls.attrchange';
  10. Use the Markup API to lazyload images and iframes

    gh-pages

    lazysizes is self-configuring and does not require JS configuration. To lazyload an element, add the lazyload class and use data-src or data-srcset instead of the standard src or srcset attributes.

    Non-responsive image:

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

    Retina optimized image:

    <img data-srcset="responsive-image1.jpg 1x, responsive-image2.jpg 2x" class="lazyload" />

    Iframe:

    <iframe frameborder="0"
    	class="lazyload"
    	allowfullscreen=""
    	data-src="//www.youtube.com/embed/ZfV-aYdU4uE">
    </iframe>
  11. Install the native loading extension

    gh-pages

    To use the native loading extension, import lazySizes and then import the plugin file. This extension automatically transforms img.lazyload or iframe.lazyload elements in browsers that support native lazy loading.

    import lazySizes from 'lazysizes';
    import 'lazysizes/plugins/native-loading/ls.native-loading';
  12. Use the object-fit extension with markup and CSS

    gh-pages

    The object-fit plugin is not a full polyfill; it requires specific CSS to function. To initialize the plugin on an image, you must apply the desired object-fit value as a font-family property directly on the image element.

    Implementation Steps:

    1. Markup: Use the lazyload class and data-srcset (with data-sizes="auto" if applicable) on your <img> tag.
    2. CSS: Set the object-fit property normally, and then set the font-family property to match the desired value (e.g., font-family: "object-fit: contain";).
    <!-- Markup -->
    <div class="imagecontainer">
    	<img class="imagecontainer-img lazyload"
    		 data-srcset="https://placehold.it/800x400 800w 400h, https://placehold.it/1200x600 1200w"
    		 data-sizes="auto" >
    </div>
    
    /* CSS */
    .imagecontainer-img {
    	object-fit: contain;
    	font-family: "object-fit: contain";
    }