如何仅在web_presentation.png变更时自动重载HTML页面避免刷新闪烁
方案1:纯JavaScript实现(无需后端,优先推荐)
直接替换你现有的页面代码即可,完全兼容Firefox浏览器,无需额外后端支持:
<html> <head> <title>web_presentation</title> <meta content="text/html; charset=utf-8" http-equiv="content-type"> <meta Name="Keywords" Content="redirect"> <meta Name="description" Content="redirect"> </head> <BODY> <img id="presentationImg" src="web_presentation.png" width="100%"> <script> // 存储上次获取的图片修改时间 let lastModifiedTime = null; // 检测间隔,单位毫秒,这里设10秒和原有刷新频率保持一致 const CHECK_INTERVAL = 10000; async function checkImageUpdate() { try { // 发HEAD请求仅获取响应头,不下载整张图片,节省带宽 const response = await fetch('web_presentation.png?' + Date.now(), { method: 'HEAD', cache: 'no-cache' }); if (!response.ok) return; const currentModified = response.headers.get('Last-Modified'); // 首次运行初始化时间 if (!lastModifiedTime) { lastModifiedTime = currentModified; return; } // 时间不一致说明图片已更新 if (currentModified !== lastModifiedTime) { lastModifiedTime = currentModified; // 预加载新图片,加载完成后再替换,避免空白/闪烁 const newImg = new Image(); newImg.onload = () => { document.getElementById('presentationImg').src = newImg.src; }; newImg.src = 'web_presentation.png?' + Date.now(); } } catch (e) { // 网络异常忽略,下次重试即可 } } // 启动定时检测 setInterval(checkImageUpdate, CHECK_INTERVAL); </script> </body> </html>
核心特性:
- 移除了原有的整页刷新逻辑,仅在图片更新时替换图片资源,无任何页面闪烁
- 采用HEAD请求仅获取响应头,带宽占用可以忽略
- 新增图片预加载逻辑,加载完成后才替换旧图,不会出现空白画面
方案2:PHP辅助实现(适合有PHP运行环境的场景)
如果你的服务器支持PHP,该方案可以避免部分服务器配置导致的Last-Modified头读取异常问题,稳定性更高:
第一步:新建get_image_mtime.php文件
<?php $imagePath = 'web_presentation.png'; if (file_exists($imagePath)) { // 返回图片的10位修改时间戳 echo filemtime($imagePath); } else { echo 0; } ?>
第二步:修改页面代码
把方案1里的checkImageUpdate函数替换为如下内容即可:
async function checkImageUpdate() { try { const response = await fetch('get_image_mtime.php?' + Date.now(), {cache: 'no-cache'}); const currentMtime = await response.text(); if (!lastModifiedTime) { lastModifiedTime = currentMtime; return; } if (currentMtime !== lastModifiedTime) { lastModifiedTime = currentMtime; const newImg = new Image(); newImg.onload = () => { document.getElementById('presentationImg').src = newImg.src; }; newImg.src = 'web_presentation.png?' + Date.now(); } } catch (e) {} }
注意事项
- 若FTP上传图片耗时较长,可在替换图片的逻辑前添加
await new Promise(resolve => setTimeout(resolve, 1000)),避免拉取到未上传完成的损坏图片 - 若存在图片缓存问题,可在服务器配置中给
web_presentation.png添加响应头Cache-Control: no-cache,确保能读取到最新的修改时间
内容的提问来源于stack exchange,提问作者xerostomus
相关产品推荐
相关产品推荐

