Last active
June 11, 2024 04:33
-
-
Save aktaumag/1f221ff4774ffb81ad0a7bf97fab46bd to your computer and use it in GitHub Desktop.
Как внедрять картинки и ускорять их.
This file contains hidden or 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
Всё о важности картинок и их ускорении |
LazyLoad для загрузки картинок при помощи CSS background
<style>
.wsBgLazy{background-image: none !important;}
</style>
<div class="wsbglazy" data-bgimgurl="image.jpg"></div>
<div class="wsbglazy" data-bgurl="image.jpg"></div>
<div class="wsbglazy"></div> <!-- картинка прописана где-то в CSS файлах стилей -->
<script>
const wsBgObserver = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
let wsEl = entry.target;
if (wsEl.dataset.bgurl) {
wsEl.style.background = "url('"+wsEl.dataset.bgurl+"') 0 0 no-repeat";
}
else if(wsEl.dataset.bgimgurl) {
wsEl.style.backgroundImage = "url('"+wsEl.dataset.bgimgurl+"')";
}
wsEl.classList.remove("wsBgLazy");
wsEl.classList.add("wsBgLoaded");
wsBgObserver.unobserve(wsEl);
}
});
});
document.addEventListener(
"DOMContentLoaded",
function () {
const wsBgMass = document.querySelectorAll(".wsBgLazy");
wsBgMass.forEach((el) => {
wsBgObserver.observe(el);
});
},
{ passive: true }
);
</script>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Источник: https://codepen.io/fe-nix/pen/PoQvxQa
Пример вставки: