diff --git a/src/CmsSlot.js b/src/CmsSlot.js index 38003527..2223f26f 100644 --- a/src/CmsSlot.js +++ b/src/CmsSlot.js @@ -24,7 +24,7 @@ export const styles = theme => ({ left: 0, }, }, - '& img[data-rsf-lazy]': { + '& img[data-src]': { visibility: 'hidden', }, }, diff --git a/src/utils/lazyLoadImages.js b/src/utils/lazyLoadImages.js index a0b6d484..bddf98bd 100644 --- a/src/utils/lazyLoadImages.js +++ b/src/utils/lazyLoadImages.js @@ -4,16 +4,25 @@ * attribute is copied to `src`. * * See https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video/ + * @param {DOMElement} element The img element to lazy load + * @param {Object} options + * @param {Object} options.lazySrcAttribute The attribute containing the image URL. Defaults to `data-src`. */ -export default function lazyLoadImages(element, { selector = 'img[data-rsf-lazy]' } = {}) { +export default function lazyLoadImages(element, { lazySrcAttribute = 'data-src' } = {}) { if (!element) return - const lazyImages = [...element.querySelectorAll(selector)] + const lazyImages = [...element.querySelectorAll(`img[${lazySrcAttribute}]`)] if (!lazyImages.length) return let lazyImageObserver const load = img => { - img.src = img.dataset.src + const src = img.getAttribute(lazySrcAttribute) + const onload = () => { + img.removeAttribute(lazySrcAttribute) + img.removeEventListener('load', onload) + } + img.addEventListener('load', onload) + img.setAttribute('src', src) if (lazyImageObserver) { lazyImageObserver.disconnect(img) diff --git a/test/utils/lazyLoadImages.test.js b/test/utils/lazyLoadImages.test.js index 01b45b34..e096fe1b 100644 --- a/test/utils/lazyLoadImages.test.js +++ b/test/utils/lazyLoadImages.test.js @@ -12,7 +12,7 @@ describe('lazyLoadImages', () => { return (
- +
) } @@ -38,7 +38,7 @@ describe('lazyLoadImages', () => { }) it('should do nothing if selector can not find anything', () => { - selector = { selector: 'test' } + selector = { lazySrcAttribute: 'data-lazy-src' } wrapper = mount() @@ -53,10 +53,10 @@ describe('lazyLoadImages', () => { // Not intersected observer.simulateChange(0, imageRef.current) expect(ref.current.src).toBeUndefined() - observer.simulateChange(1, imageRef.current) - - expect(imageRef.current.src).toBe('https://via.placeholder.com/600x600') + expect(imageRef.current.getAttribute('src')).toBe('https://via.placeholder.com/600x600') + imageRef.current.dispatchEvent(new Event('load')) + expect(imageRef.current.getAttribute('data-src')).toBe(null) }) describe('if intersection observer is not available', () => {