在网络中延迟加载 Lottie JSON

问题描述 投票:0回答:2

使用lottie-web(javascript)时有什么方法可以延迟加载lottie JSON文件吗? 现在我的代码是;

lottie.loadAnimation({
   container: document.querySelector('#lottie-1'),
   renderer: 'svg',
   loop: true,
   autoplay: true,
   path: 'https://assets10.lottiefiles.com/packages/lf20_wzcckjq4.json'
});

因为上面的代码在 Pagespeed Insights 中显示为巨大的网络负载(在我的例子中总计约为 20MB)。
我尝试将其放在 DOMContentLoaded、readyStatecomplete、windowonload 甚至 setTimeout 中。

javascript lottie
2个回答
1
投票

使用“滚动”事件侦听器并在 window.onload 中模拟滚动事件对我有用。

<script>
var sc=0;
window.addEventListener('scroll', function() {
    if(sc == 0){
        sc=1;
        lottie.loadAnimation({
            container: document.querySelector('#lottie-1'),
            renderer: 'svg',
            loop: true,
            autoplay: true,
            path: 'https://assets10.lottiefiles.com/packages/lf20_wzcckjq4.json'
        });
    }
});
window.onload = function() {
    window.scrollTo(window.scrollX, window.scrollY - 1);
    window.scrollTo(window.scrollX, window.scrollY + 1);
};
</script>

0
投票

我没有使用

<lottie-player ...>
元素,而是使用了这样的标记:

<lottie-player-lazy id="lottie" src="my-lottie.json"></lottie-player-lazy>

然后我使用拦截观察器仅当它进入浏览器视口时才加载它:

        const element = document.querySelector('#lottie');

        const observer = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                // If the element is in the viewport
                if (entry.isIntersecting) {

                    observer.unobserve(entry.target);


                        // Create a new element of the desired type
                        const newElement = $('<lottie-player></lottie-player>');

                        // Copy the attributes from the old element to the new one
                        element.each(this.attributes, function() {
                            if (this.specified) {
                                newElement.attr(this.name, this.value);
                            }
                        });

                        // Replace the old element with the new one
                        $(element).replaceWith(newElement);

                }
            });
        });
© www.soinside.com 2019 - 2024. All rights reserved.