脚本如何校验图片懒加载效果

wen 实用脚本 30

本文目录导读:

脚本如何校验图片懒加载效果

  1. 使用浏览器开发者工具
  2. Intersection Observer 验证
  3. 自动化测试脚本
  4. 性能监控脚本
  5. 浏览器扩展自动化
  6. 简单的验证方法
  7. 使用建议

使用浏览器开发者工具

查看网络请求

// 在控制台中执行,查看图片是否被延迟加载
// 滚动页面时观察Network面板中的图片请求
// 检查哪些图片还没有加载
const lazyImages = document.querySelectorAll('img[loading="lazy"]');
console.log('懒加载图片总数:', lazyImages.length);
// 检查已加载的图片
const loadedImages = document.querySelectorAll('img[loading="lazy"][complete]');
console.log('已加载图片数:', loadedImages.length);

Intersection Observer 验证

// 创建一个观察器来检测图片懒加载
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            console.log('图片进入视口:', entry.target.src || entry.target.dataset.src);
        }
    });
}, {
    rootMargin: '50px 0px', // 提前50px触发
    threshold: 0.1
});
// 观察所有懒加载图片
document.querySelectorAll('[data-src], [loading="lazy"]').forEach(img => {
    observer.observe(img);
});

自动化测试脚本

class LazyLoadTester {
    constructor() {
        this.loadedImages = new Set();
        this.startTime = Date.now();
    }
    // 测试图片是否被延迟加载
    async testLazyLoading(pageUrl) {
        console.log(`测试页面: ${pageUrl}`);
        // 获取所有图片
        const allImages = document.querySelectorAll('img');
        const lazyImages = document.querySelectorAll('img[loading="lazy"], [data-src]');
        console.log(`总图片数: ${allImages.length}`);
        console.log(`懒加载图片数: ${lazyImages.length}`);
        // 记录初始加载状态
        const initialLoaded = this.getLoadedImages();
        console.log('初始已加载图片:', initialLoaded.size);
        // 模拟滚动
        await this.simulateScroll();
        // 记录滚动后加载状态
        const afterScroll = this.getLoadedImages();
        console.log('滚动后加载的图片:', afterScroll.size - initialLoaded.size);
        return {
            total: allImages.length,
            lazyLoaded: lazyImages.length,
            initiallyLoaded: initialLoaded.size,
            loadedAfterScroll: afterScroll.size - initialLoaded.size
        };
    }
    // 获取已加载的图片
    getLoadedImages() {
        const loaded = new Set();
        document.querySelectorAll('img').forEach(img => {
            if (img.complete && img.naturalHeight !== 0) {
                loaded.add(img.src);
            }
        });
        return loaded;
    }
    // 模拟页面滚动
    async simulateScroll() {
        const scrollHeight = document.documentElement.scrollHeight;
        const viewportHeight = window.innerHeight;
        const steps = 10;
        const stepSize = scrollHeight / steps;
        for (let i = 0; i <= steps; i++) {
            window.scrollTo(0, i * stepSize);
            await this.sleep(500); // 等待图片加载
        }
        // 滚回顶部
        window.scrollTo(0, 0);
    }
    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}
// 使用示例
const tester = new LazyLoadTester();
tester.testLazyLoading(window.location.href);

性能监控脚本

class PerformanceMonitor {
    constructor() {
        this.performanceEntries = [];
    }
    // 监控图片加载性能
    monitorImageLoading() {
        // 使用 Performance API
        if (window.performance && window.performance.getEntriesByType) {
            const resources = performance.getEntriesByType('resource');
            resources.filter(resource => 
                resource.initiatorType === 'img'
            ).forEach(img => {
                this.performanceEntries.push({
                    url: img.name,
                    startTime: img.startTime,
                    duration: img.duration,
                    loaded: img.responseEnd > 0
                });
            });
        }
        // 使用 PerformanceObserver
        if (window.PerformanceObserver) {
            const observer = new PerformanceObserver((list) => {
                list.getEntries().forEach(entry => {
                    if (entry.initiatorType === 'img') {
                        console.log('图片加载:', {
                            url: entry.name,
                            duration: entry.duration,
                            size: entry.transferSize
                        });
                    }
                });
            });
            observer.observe({ entryTypes: ['resource'] });
        }
    }
    // 检查懒加载是否生效
    checkLazyLoadEffectiveness() {
        const lazyImages = document.querySelectorAll('[data-src]');
        let immediateLoads = 0;
        lazyImages.forEach(img => {
            const rect = img.getBoundingClientRect();
            // 检查不在视口中的图片是否立即加载
            if (rect.top > window.innerHeight && img.complete) {
                immediateLoads++;
            }
        });
        return {
            totalLazyImages: lazyImages.length,
            prematureLoads: immediateLoads,
            effectiveness: ((lazyImages.length - immediateLoads) / lazyImages.length * 100).toFixed(2) + '%'
        };
    }
}
// 使用
const monitor = new PerformanceMonitor();
monitor.monitorImageLoading();
console.log('懒加载效果:', monitor.checkLazyLoadEffectiveness());

浏览器扩展自动化

// Puppeteer 自动化测试示例
const puppeteer = require('puppeteer');
async function testLazyLoad(url) {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    // 拦截网络请求
    await page.setRequestInterception(true);
    const imageRequests = [];
    page.on('request', request => {
        if (request.resourceType() === 'image') {
            imageRequests.push({
                url: request.url(),
                time: Date.now()
            });
        }
        request.continue();
    });
    await page.goto(url, { waitUntil: 'networkidle0' });
    console.log('初始加载的图片数:', imageRequests.length);
    // 模拟滚动
    await page.evaluate(async () => {
        const distance = 500;
        const totalHeight = document.body.scrollHeight;
        let scrolled = 0;
        while (scrolled < totalHeight) {
            window.scrollBy(0, distance);
            scrolled += distance;
            await new Promise(resolve => setTimeout(resolve, 200));
        }
    });
    console.log('总共加载的图片数:', imageRequests.length);
    await browser.close();
    return imageRequests;
}

简单的验证方法

<!-- 在页面中添加调试信息 -->
<script>
// 实时显示懒加载状态
setInterval(() => {
    const allImgs = document.querySelectorAll('img');
    const loadedImgs = document.querySelectorAll('img[complete]');
    const lazyImgs = document.querySelectorAll('[data-src]');
    console.table({
        '总图片数': allImgs.length,
        '已加载数': loadedImgs.length,
        '懒加载数': lazyImgs.length,
        '加载百分比': ((loadedImgs.length / allImgs.length) * 100).toFixed(2) + '%'
    });
}, 2000);
// 在图片加载时添加视觉反馈
document.querySelectorAll('[data-src]').forEach(img => {
    img.style.border = '2px solid red';
    img.addEventListener('load', function() {
        this.style.border = '2px solid green';
        console.log('懒加载完成:', this.dataset.src);
    });
});
</script>

使用建议

  1. 开发阶段:使用浏览器DevTools的Network面板实时监控
  2. 测试阶段:使用自动化脚本进行多场景测试
  3. 生产环境:使用Performance API监控性能指标
  4. 持续监控:集成到CI/CD流程中定期检查

这些方法可以帮助你全面验证图片懒加载是否正常工作。

抱歉,评论功能暂时关闭!