I used a clever technique to create a blur effect by loading a small, lightweight image first. Once the main background image is loaded, it swaps out the 'data-src' with the actual image.
However, I am facing an issue with the abrupt transition, causing the background image to flicker. I am looking for a solution to smoothly transition with a fade effect instead.
Here is the code snippet:
function init() {
let imgDefer = document.querySelectorAll('[data-src]');
for (let i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
if (imgDefer[i].tagName === 'IMG') {
imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src'));
} else {
let style = "background-image:url({url})";
imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));
}
}
}
}
And here is how the element is structured:
<header class="header header-inverse h-fullscreen p-0 overflow-hidden" data-src="assets/img/headerbg.jpg" style="background-image: url('assets/img/headerbgprev.jpg');"> ... </header>