dkern / jquery.lazy

A lightweight, fast, feature-rich, powerful and highly configurable delayed content, image and background lazy loading plugin for jQuery & Zepto.
http://jquery.eisbehr.de/lazy
Other
1.02k stars 236 forks source link

Lazy loading a SVG with PNG (standard and retina) fallback #190

Closed SlimDeluxe closed 5 years ago

SlimDeluxe commented 5 years ago

I am interested if there's a way to lazy load a SVG while also providing a fallback with PNGs (one for standard and one for retina displays). Non-SVG capable browsers are still at cca. 5% worldwide.

I use modernizr for feature testing, so my div with a background looks like this (in LESS):

.contact {
    background-image: url(/assets/dist/img/contact.svg);
    .no-svg & {
        .img-retina("/assets/dist/img/contact.png", "/assets/dist/img/contact@2x.png", 373px, 193px);
    }
}

Is there a way to implement this with the Lazy plugin while having only 1 DOM element or should I use 2 and then show the correct one (considering SVG support)?

dkern commented 5 years ago

I would build something by myself. For example, if you have a tool like modernizr to determine support, you could initialize Lazy with different option. You could set the used attribute names to let Lazy select the correct images.

$('.lazy').lazy({
  attribute: hasSvg ? 'data-svg' : 'data-src',
  retinaAttribute:  hasSvg ? 'data-retina-svg' : 'data-retina-src'
});
<img data-svg="default.svg" data-retina-svg="retina.svg" data-src="default.png" data-retina-src="retina.png" />
SlimDeluxe commented 4 years ago

Hi, thank you and sorry for the very late reply. Your suggestion works perfectly. Using actual Modernizr it looks like this:

$('.lazy-svg').lazy({
    attribute: Modernizr.svg ? 'data-svg' : 'data-src',
    retinaAttribute: Modernizr.svg ? 'data-svg' : 'data-retina',
});

Using the lazy-svg class to target imgs/divs that use SVGs :slightly_smiling_face: To test it, I set Modernizr.svg to false right before the initialization.