-
Notifications
You must be signed in to change notification settings - Fork 2
Lazy load background images in HTML
optimalisatie edited this page Aug 2, 2020
·
2 revisions
$lazy can be used to lazy load background images, both in HTML and in stylesheets using its $lazybg extension. This Wiki shows how to lazy load background images in HTML.
To lazy load background images in the HTML requires a HTML filter that rewrites background-image
in inline styles to a custom data attribute. The Style.Tools PHP library and CMS plugins provide easy solutions to setup a HTML filter for this purpose.
Example:
<!-- before -->
<div style="background-image:url('/image.jpg');">...</div>
<!-- after -->
<div data-zbg="/image.jpg">...</div>
The following $lazy code shows how to lazy load the background images.
// lazy load *[data-zbg] elements
$lazy('[data-zbg]', function(el) {
var bg = el.getAttribute('data-zbg');
if (bg) {
// optional: convert to WebP
// The $lazy+webp extension provides the method $zwebp() that can convert image URLs to .webp.
bg = $zwebp(bg);
// render background image
el.style.backgroundImage = 'url(' + bg + ')';
// optional: apply requestAnimationFrame timing method from $async
//$async.time('requestAnimationFrame', function() {
// el.style.backgroundImage = 'url(' + bg + ')';
//});
el.removeAttribute('data-zbg'); // optional, sanitize HTML
}
});