Skip to content

1.1.0

Compare
Choose a tag to compare
@optimalisatie optimalisatie released this 08 Aug 20:58
· 61 commits to master since this release
  • Added: .webp rewrite with fallback (WebP support for <img> tag)
  • Added: inview and out-of-view callback (persistent observer)
  • Removed: CustomEvent (can be manually added via inview callback)
  • $lazybg for lazy loading of background-image in stylesheets
  • Tiny lazy load script renamed to $z() (300 bytes).

Warning: the custom observer callback has been moved to the third argument and the dist/* file names have been changed.

Documentation: https://docs.style.tools/lazy/lazy

Lazy loading of background-image in stylesheets

dist/lazybg.js enables to lazy load background images in stylesheets. It makes use of CSS Variables with a fallback for old browsers.

There are four options to resolve images:

  1. manually define images via :root {} within the stylesheet
  2. base64 encode image URLs
  3. provide a JSON source list as resolver
  4. provide a javascript function as resolver
/* :root based pre-configured value */
:root {
  --z--lazy-img: url('/image.jpg');
}
footer {
  background-image: url('/image.jpg'); // old browsers
  background-image: var(--z-lazy-img, none);
}

/* base64 encoded value */
p#out-of-view {
  background-image: url('/image.jpg'); // old browsers
  background-image: var(--z-base64_value, none); /* note: requires character replacements, see documentation */
}

/* JSON object or javascript function based custom resolver */
div#out-of-view {
  background-image: url('/image.jpg'); // old browsers
  background-image: var(--z-custom-resolved, none); 
}
<script src="dist/lazybg.js"></script>
<script>
// default: document.styleSheets
$lazybg(); 

// custom $lazy config
$lazybg(
  document.querySelectorAll('link[rel=stylesheet], style#other'),
  {
    observer: {
      threshold: 0,
      rootMargin: '100px'
    }
  }
); 

// custom JSON based resolver
$lazybg(
  0,0, // default config

  // resolver
  {
    "custom-resolved": "url('/image.jpg')"
  }
); 

// custom javascript based resolver
$lazybg(
  0,0, // default config

  // resolver
  function(key) {

    // resolve key "custon-resolved"
    return "url('/"+key+".jpg');"
  }
); 
</script>

Base64 encoded image value

CSS variables are limited to DOMString. The following characters need to be replaced in a base64 encoded value:

/:

=:

Automatic .webp rewrite

It is possible to automatically load .webp images for browsers that support Google's WebP format. It saves a server-side redirect and it adds WebP support to the <img> tag.

Simply use the dist/lazy+webp... files to enable it.

The solution uses <img onerror> to fallback to the original image when the .webp image is 404.

To manually disable webp rewrites for an image add the HTML attribute data-webp="no". To disable it for a specific $lazy configuration, set the 4th argument to false.

$lazybg supports WebP rewrites by using dist/lazybg+webp.js.