You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript防止图片缓存问题:重复调用函数图片不更新

解决图片缓存导致重复显示同一图片的问题

问题根源是浏览器会缓存相同URL的资源,每次请求https://picsum.photos/200/300时,直接读取本地缓存而非重新请求新图。只需让每次请求的URL唯一,就能绕过缓存,具体有两种简单方法:

方法一:添加时间戳参数

时间戳是当前时间的毫秒数,每次调用都会生成唯一值,确保URL不同:

function grabImg(){
    var img = document.createElement('img');
    // 拼接时间戳作为查询参数
    img.src = 'https://picsum.photos/200/300?' + new Date().getTime();
    document.getElementById('flex-cat').appendChild(img);
}

方法二:添加随机数参数

用Math.random()生成0-1之间的随机小数,同样能让URL唯一:

function grabImg(){
    var img = document.createElement('img');
    // 拼接随机数作为查询参数
    img.src = 'https://picsum.photos/200/300?rand=' + Math.random();
    document.getElementById('flex-cat').appendChild(img);
}

两种方法原理一致:通过修改URL的查询部分,让浏览器判定为新资源,从而发起新请求获取不同的随机图片,无需改动HTML结构。

内容的提问来源于stack exchange,提问作者Clifford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:30:42