代码 1 0

    Typecho如何实现图片懒加载

    方法1 使用原生js

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取所有图片(如果主题默认输出 src,可以动态替换为 data-src)
        const images = document.querySelectorAll('img[src]:not([data-src])');
        
        // 防止重复处理
        images.forEach(img => {
            if (!img.getAttribute('data-src')) {
                img.setAttribute('data-src', img.src); // 把 src 存到 data-src
                img.removeAttribute('src'); // 移除 src,避免立即加载
            }
        });
    
        // 懒加载逻辑
        const lazyLoad = (targets) => {
            if ('IntersectionObserver' in window) {
                const observer = new IntersectionObserver((entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const img = entry.target;
                            img.src = img.dataset.src;
                            observer.unobserve(img); // 加载后停止观察
                        }
                    });
                });
                targets.forEach(img => observer.observe(img));
            } else {
                // 兼容旧浏览器(滚动监听)
                const checkImages = () => {
                    targets.forEach(img => {
                        const rect = img.getBoundingClientRect();
                        if (rect.top < window.innerHeight + 100) { // 提前 100px 加载
                            img.src = img.dataset.src;
                        }
                    });
                };
                window.addEventListener('scroll', checkImages);
                checkImages(); // 初始检查
            }
        };
    
        // 对所有 data-src 图片应用懒加载
        lazyLoad(document.querySelectorAll('img[data-src]'));
    });
    </script>

    方法2 使用php

    仅支持现代浏览器

    $content = preg_replace('/<img(.*?)src="(.*?)"(.*?)>/i', '<img$1src="$2" loading="lazy"$3>', $this->content);
    echo $content;

    方法3 使用第三方库

    <script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.2/lazysizes.min.js" async></script>
    <img data-src="image.jpg" class="lazyload" alt="示例图片">
    .lazyload {
        background: #f0f0f0;
    }

    方法3可与方法2同时使用以提高兼容性