karsttech.com/layouts/partials/background-images.html

35 lines
No EOL
1.2 KiB
HTML

{{ $images := slice }}
{{ range readDir "static/backgrounds" }}
{{ if or (in .Name ".webp") (in .Name ".jpg") }}
{{ $images = $images | append .Name }}
{{ end }}
{{ end }}
<div class="background-container">
<img id="background-thumb" alt="Background" class="background-image">
<img id="background-full" alt="Background" class="background-image background-full" loading="lazy">
<script>
const images = {{ $images }};
const randomImage = images[Math.floor(Math.random() * images.length)];
const thumbImg = document.getElementById('background-thumb');
const fullImg = document.getElementById('background-full');
const thumbPath = `/backgrounds/thumbs/${randomImage}`;
const fullPath = `/backgrounds/${randomImage}`;
thumbImg.src = thumbPath;
setTimeout(() => {
const preloadImg = new Image();
preloadImg.onload = () => {
fullImg.src = fullPath;
fullImg.classList.add('loaded');
setTimeout(() => thumbImg.remove(), 2000);
};
preloadImg.onerror = () => {
fullImg.src = fullPath;
fullImg.classList.add('loaded');
};
preloadImg.src = fullPath;
}, 800);
</script>
</div>