交叉路口观察员API-背景图像

时间:2018-11-26 12:08:28

标签: javascript image performance lazy-loading

我正在尝试为嵌入式背景图像(用于延迟加载)实现Intersection Observer API。但是,它是404处理并返回未定义的错误。内联背景图像的原因是该网站在WordPress上运行,因此需要从媒体库中提取图像。

JS和CSS位于页脚中,我尝试将其放在首位,但没有成功。它确实适用于常规img标签,但不适用于背景图片。

代码如下:

HTML

<div class="image js-img" style="background-image:url('<?= $image ?>');">

CSS

 .js-img.fade {
    animation-name: fadeIn;
    animation-duration: 400ms;
    animation-fill-mode: forwards;
    animation-timing-function: ease-in;
}        

@keyframes fadeIn {
    0% { opacity: 0; }
    100% { opacity: 1; }
}

JS

const images = document.querySelectorAll('.js-img');

if(!('IntersectionObserver' in window)) {
    images.forEach(image => {
        handleImage(image);
    })
} else {
    let config = {
        rootMargin: '100px 0px',
        threshold: 0.01
    };
    let observer = new IntersectionObserver(observeImages, config);

    images.forEach(image => {
        observer.observe(image);
    }) 

    function observeImages(entries) {
        entries.forEach(entry => {
            if(entry.intersectionRatio > 0) {
                observer.unobserve(entry.target);
                handleImage(entry.target);
            }
        })
    } 
}

function handleImage(el) {
    preloadImage(el.dataset.src).then(src => {
        el.tagName === 'IMG' ?
            el.src = src :
            el.style.backgroundImage = 'url('+ src +')';

        el.classList.add('fade');
        el.removeAttribute('data-src');
    })    
}

function preloadImage(url) {
    return new Promise((resolve,reject) => {
        let image = new Image();
        image.load = resolve(url);
        image.error = reject;
        image.src = url;
    })
}

0 个答案:

没有答案