nabrown / unveil-intersect

A lazy-loading JS plugin using the Intersection Observer API, with fallback

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

unveil.js - A lightweight Javascript plugin to lazy load images

Usage

<p class="link-to-unlazy">Images not loading? Sorry about that. <a href="index-unlazy.html">Try this page instead.</a></p>
<img src="img/placeholder-v.png" class="unveil" 
  data-src="img/purple-gills-700.jpg"
  data-srcset="img/purple-gills-1400.jpg 1400w, img/purple-gills-2800.jpg 2800w"
  alt="A small mushroom with pink-purple, widly-spaced gills, lying on a green mossy background."
/>
...

<script>
  document.querySelector('#link-to-unlazy');
  window.unveil(300, function(){
    //... do stuff
  });
</script>  

Set the src to a placeholder image with the same proportions as your final image. Or, use a relatively low-resolution version of your image.

Then use data-src and data-srcset as you normally would use src and srcset.

The two arguments are:

  • a "look-ahead" distance (in px) to start loading images before they reach the browser viewport.
  • a callback function

For a lightweight fallback for users without Javascript, add a link to a plain html page.

--

The fallback is a vanilla-js rewrite of Luis Almeda's original. For more on the translation process, check out my write-up on Medium.

License

Unveil is licensed under the MIT license.

About

A lazy-loading JS plugin using the Intersection Observer API, with fallback


Languages

Language:JavaScript 47.1%Language:HTML 45.6%Language:CSS 7.3%