Created
November 21, 2019 16:47
-
-
Save javimata/9d893ef74f9f6ec503469b0e36220fa7 to your computer and use it in GitHub Desktop.
Script para lazyload de images y backgrounds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if ("IntersectionObserver" in window) { | |
const lazyImages = document.querySelectorAll('[data-src]'); | |
const lazyBGs = document.querySelectorAll('[data-background]'); | |
const options = { threshold: 0 }; | |
const imageObserver = new IntersectionObserver( | |
(entries, observer) => { | |
entries.forEach(entry => { | |
if (entry.isIntersecting) { | |
const image = entry.target; | |
image.src = image.dataset.src; | |
imageObserver.unobserve(image); | |
} | |
}); | |
}, options); | |
const bgObserver = new IntersectionObserver( | |
(entries, observer) => { | |
entries.forEach(entry => { | |
if (entry.isIntersecting) { | |
const imagebg = entry.target; | |
imagebg.style.backgroundImage = "url('"+imagebg.dataset.background+"')"; | |
imagebg.classList.add('bg-active'); | |
bgObserver.unobserve(imagebg); | |
} | |
}); | |
}, options); | |
lazyImages.forEach(image => imageObserver.observe(image)); | |
lazyBGs.forEach( imagebg => bgObserver.observe(imagebg)); | |
} else { | |
function init() { | |
var imgDefer = document.getElementsByTagName('img'); | |
for (var i = 0; i < imgDefer.length; i++) { | |
if (imgDefer[i].getAttribute('data-src')) { | |
imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src')); | |
} | |
} | |
} | |
window.onload = init; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
¿Como funciona?
Agrega el script al final de tu código, ya sea como un archivo separado o dentro de algún archivo de javascript que ya cargues y de preferencia arriba del mismo.En el html cambia las etiquetas img por algo así:
<img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="images/imagen1.jpg" alt="Imagen">
Donde el atributo src cargará una imagen transparente de 1px y cuando está deba ser cargada será sustituida por la imagen indicada en el atributo data-src
Para los fondos, en el elemento a colocarlo debes agregar un atributo data-background con la url de la imagen de fondo, por ejemplo:
<div class="box" data-background="images/background.jpg"><div>
La ruta tanto del data-src como del data-background son relativas al html o absolutas.
OJO
El fondo solo colocará un style dentro de la etiqueta con el css background-image, si requieres que lleve más estilos estos debes colocarlos dentro del css, por ejemplo el background-repeat, background-size, etc...