$(function () { // WebP支持检测(首次运行时缓存结果) function checkWebPSupport(callback) { if (typeof localStorage !== 'undefined' && localStorage.getItem('webpSupport') !== null) { return callback(localStorage.getItem('webpSupport') === 'true'); } const img = new Image(); img.onload = function () { const result = img.width > 0 && img.height > 0; localStorage.setItem('webpSupport', result); callback(result); }; img.onerror = function () { localStorage.setItem('webpSupport', false); callback(false); }; img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='; } checkWebPSupport(function (isSupported) { $('img').each(function () { const $img = $(this); const webpSrc = $img.closest('picture').find('source[type="image/webp"]').data('srcset'); const fallbackSrc = $img.data('src'); // 动态设置真实图片路径 $img.data('original', isSupported ? webpSrc : fallbackSrc); }); $('img').lazyload({ threshold: 200, effect: 'fadeIn', appear: function () { const realSrc = $(this).data('original'); $(this).attr('src', realSrc); $(this).addClass('lazy-loaded'); }, load: function () { $(this).addClass('lazy-loaded'); }, error: function () { $(this).attr('src', 'img/error.jpg'); }, }); }); // 初始化懒加载 $('img').lazyload({ effect: 'fadeIn', // 淡入效果 threshold: 100, // 提前300px加载 failure_limit: 15, // 最大容错数量 skip_invisible: true, // 加载隐藏图片 appear: function () { // 加载前回调 $(this).css('background', 'transparent'); $(this).removeClass('lazyload'); }, load: function () { // 加载完成回调 $(this).addClass('lazy-loaded'); }, }); });