开发HTML/JS页面:实现闪屏图与更新图的自动切换逻辑
最优实现方案
核心思路
通过定时检查latest.jpg的文件修改时间判断是否被更新;更新后切换显示该图90秒,随后自动切回splash.jpg,同时规避浏览器缓存干扰。
HTML结构
<!DOCTYPE html> <html> <head> <style> body { margin: 0; } img { width: 100vw; height: 100vh; object-fit: cover; } </style> </head> <body> <img id="displayImg" src="splash.jpg" alt="Splash Screen"> <script src="script.js"></script> </body> </html>
JavaScript逻辑
const imgElement = document.getElementById('displayImg'); let currentImage = 'splash'; // 标记当前显示的图片类型 let lastModifiedTime = null; // 存储latest.jpg的最后修改时间 let switchTimer = null; // 控制切回闪屏的定时器 const CHECK_INTERVAL = 2000; // 检查更新的间隔(单位:毫秒,可按需调整) // 检查latest.jpg是否更新 async function checkLatestImage() { // 当前显示latest时跳过检查,避免重复触发 if (currentImage === 'latest') return; try { // 用HEAD请求获取文件头,仅拿元数据不下载图片,节省资源 const response = await fetch('latest.jpg', { method: 'HEAD', cache: 'no-store' // 强制禁用缓存,确保获取最新的文件头 }); if (!response.ok) throw new Error('获取图片信息失败'); const newModifiedTime = response.headers.get('Last-Modified'); // 首次检查时初始化修改时间 if (!lastModifiedTime) { lastModifiedTime = newModifiedTime; return; } // 修改时间变化,说明文件被覆盖更新 if (newModifiedTime !== lastModifiedTime) { lastModifiedTime = newModifiedTime; switchToLatest(); } } catch (err) { console.error('检查图片更新出错:', err); } } // 切换到latest.jpg并启动倒计时切回 function switchToLatest() { currentImage = 'latest'; // 追加时间戳参数,避免浏览器加载缓存的旧图片 imgElement.src = `latest.jpg?t=${Date.now()}`; // 清除之前的定时器(防止重复计时) if (switchTimer) clearTimeout(switchTimer); // 90秒后自动切回闪屏图 switchTimer = setTimeout(() => { currentImage = 'splash'; imgElement.src = 'splash.jpg'; }, 90000); } // 启动定时检查任务 setInterval(checkLatestImage, CHECK_INTERVAL); // 页面加载完成后立即执行一次检查 checkLatestImage();
关键细节说明
- HEAD请求优化:仅获取文件的Last-Modified头信息,比GET请求更高效,减少带宽消耗
- 缓存控制:
cache: 'no-store'确保每次检查都拿到服务器端最新的文件状态;切换图片时追加时间戳,避免浏览器缓存旧图 - 状态管理:标记当前显示的图片类型,避免在显示latest时重复触发检查逻辑
- 定时器安全:切换图片时清除旧定时器,防止多个计时任务冲突
内容的提问来源于stack exchange,提问作者Wes Henderson
相关产品推荐
相关产品推荐

