Imagen progresiva carga diferida con efecto de desenfoque
| Autor: | derekmorash |
|---|---|
| Views Total: | 3,196 |
| Sitio oficial: | Ir a la web |
| Actualizado: | June 3, 2017 |
| Licencia: | MIT |
Vista prévia
Descripción
Un pequeño script para cargar progresivamente imágenes con un efecto de desenfoque. El script mostrará su imagen de baja resolución con un desenfoque progresivo hasta que la imagen de alta resolución se haya cargado por completo.
Funcionamiento
Añade las imágenes de baja resolución y alta resolución a la página web como esta:
<a class="card-image" href="#" style="background-image: url(https://unsplash.it/100/100?image=758);" data-image-full="https://unsplash.it/500/500?image=758"> <img src="https://unsplash.it/100/100?image=758" alt="Eli DeFaria" /> </a>
Los estilos CSS requeridos para el efecto de carga diferida de la imagen.
.card-image {
display: block;
min-height: 20rem; /* layout hack */
background: #fff center center no-repeat;
background-size: cover;
filter: blur(3px); /* blur the lowres image */
}
.card-image > img {
display: block;
width: 100%;
opacity: 0; /* visually hide the img element */
}
.card-image.is-loaded {
filter: none; /* remove the blur on fullres image */
transition: filter 1s;
} El núcleo JavaScript para activar el efecto de carga perezosa de la imagen.
window.addEventListener('load', function() {
// setTimeout to simulate the delay from a real page load
setTimeout(lazyLoad, 1000);
});
function lazyLoad() {
var card_images = document.querySelectorAll('.card-image');
// loop over each card image
card_images.forEach(function(card_image) {
var image_url = card_image.getAttribute('data-image-full');
var content_image = card_image.querySelector('img');
// change the src of the content image to load the new high res photo
content_image.src = image_url;
// listen for load event when the new photo is finished loading
content_image.addEventListener('load', function() {
// swap out the visible background image with the new fully downloaded photo
card_image.style.backgroundImage = 'url(' + image_url + ')';
// add a class to remove the blur filter to smoothly transition the image change
card_image.className = card_image.className + ' is-loaded';
});
});
}





