Skip to content

Commit

Permalink
Added lazy loading for css bg images
Browse files Browse the repository at this point in the history
  • Loading branch information
lrotermund committed Oct 21, 2024
1 parent 82f8289 commit 88b1413
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
20 changes: 20 additions & 0 deletions assets/js/template-dom-scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,23 @@
});

}());

document.addEventListener("DOMContentLoaded", function() {
const lazyBackgrounds = document.querySelectorAll('.lazy-background');

const lazyLoadBackground = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const bg = entry.target.getAttribute('data-bg');
entry.target.style.backgroundImage = bg;
observer.unobserve(entry.target);
}
});
};

const observer = new IntersectionObserver(lazyLoadBackground);

lazyBackgrounds.forEach(background => {
observer.observe(background);
});
});
7 changes: 7 additions & 0 deletions layouts/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,17 @@ <h1>{{ .Title }}</h1>
<div class="meta">
{{$images := apply $p.Params.images "absURL" "."}} {{$postImage :=
index $images 0}}
{{ if lt $i 3 }}
<div
class="photo"
style="background-image: url({{ $postImage }})"
></div>
{{ else }}
<div
class="photo lazy-background"
data-bg="url({{ $postImage }})"
></div>
{{ end }}
</div>
<div class="description">
<h2>{{ $p.Title }}</h2>
Expand Down

0 comments on commit 88b1413

Please sign in to comment.