Lazyload for Webflow Images

For all of you that have been struggling with lazy-loading CMS images, I have managed to get it done using Lazysizes and noscript method.

More: javascript - DRY lazy-loaded images with <noscript> fallback - Stack Overflow

Step 1: Paste this into custom code:

 <script>
(function(){
    'use strict';

    var supportPicture = !!window.HTMLPictureElement;

    addEventListener('lazybeforeunveil', function(e){
        if(e.defaultPrevented || e.target.getAttribute('data-noscript') == null){return;}
        var imgs, i;
        var noScript = e.target.getElementsByTagName('noscript')[0] || {};
        var content = noScript.textContent || noScript.innerText || '';
        e.target.innerHTML = content;

        if(supportPicture){return;}

        imgs = e.target.querySelectorAll('img[srcset], picture > img');

        for(i = 0; i < imgs.length; i++){
            lazySizes.uP(imgs[i]);
        }
    });
})();
</script>


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

<script>
$(document).ready(function() {

	window.lazySizesConfig = window.lazySizesConfig || {};
	window.lazySizesConfig.init = false;

	$('.lazyload').each(function() {
		$(this).attr('data-src', $(this).attr('src'));
		$(this).removeAttr('src');
		$(this).attr('data-srcset', $(this).attr('srcset'));
		$(this).removeAttr('srcset');
		$(this).removeAttr('sizes');
		$(this).attr('data-sizes', 'auto');

		lazySizes.init();
	});

});
</script>

Step 2: Include a “HTML embed 1” right before and “HTML embed 2” right after every photo/video/iframe/whatever you want to lazyload. Works with responsive images!

HTML Embed 1:

<div class="lazyload" data-noscript="">
<noscript>

HTML Embed 2:

</noscript></div>

So it looks quite tidy in the Designer:

10

15 Likes