Medium Like Progressive Image Loading Effect

Category: Javascript , Loading | February 4, 2020
Author:Lógico
Views Total:2,240 views
Official Page:Go to website
Last Update:February 4, 2020
License:MIT

Preview:

Medium Like Progressive Image Loading Effect

Description:

A simple JavaScript & CSS implementation of the Medium-style progressive image loading effect.

It first loads a small blurry image and then fades into the large version when the image is completely loaded.

Note that Lazy load behavior is not integrated. To enable, you might need a 3rd image lazy loader or use the native browser lazy load behavior.

How to use it:

1. Add the blurry image to the page.

<img class="blur" src="small.jpg" />

2. Wrap the image into a DIV container and define the path to the full image in the data-src attribute.

<div class="medium-img" data-src="full.jpg">
  <img class="blur" src="small.jpg" />
</div>

3. Insert the full image into the noscript tag. Ideal for those users who disabled JavaScript in their browser.

<div class="medium-img" data-src="full.jpg">
  <img class="blur" src="small.jpg" />
  <noscript>
    <img src="full.jpg" />
  </noscript>
</div>

4. Create the blur & fade in effects in the CSS.

.blur {
  filter: blur(25px);
  animation-name: example;
  animation-duration: .5s;
  animation-delay: .5s;
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
}
.no-blur {
  filter: blur(0);
  transition: filter .5s 2s ease-in;
}
@keyframes example {
  from {opacity: 0;}
  to {opacity: 1;}
}

5. The main script to enable the image loading effect on page load.

window.addEventListener("load", function () {
  let lazy = document.getElementsByClassName('medium-img');
  for (let n = 0, len = lazy.length; n < len; n++) {
    lazy[0].children[0].setAttribute('src', lazy[0].getAttribute('data-src'));
    lazy[0].children[0].classList.add('no-blur');
  }
});

You Might Be Interested In:


Leave a Reply