在浏览器中缓存图像后,通过请求图像来检查互联网连接不起作用

Checking of internet connection by requesting an image does not work after the image gets cached in the browser

本文关键字:图像 检查 请求 互联网 不起作用 连接 浏览器 缓存      更新时间:2023-09-26

在浏览器中缓存图像后,通过请求图像来检查互联网连接不工作。在一两次之后,这不起作用,因为图像存储在浏览器的缓存中,所以有什么解决方案吗?或者我需要检查连接是否可用?window.navigator.online不可靠。所以寻找其他有趣可靠的解决方案

使用cache buster查询字符串。querystring强制浏览器检查服务器是否有新图像。

yourImageObj.src = "newImage.png?time=" + new Date().getTime();

使用XMLHttpRequest对象和POST协议。POST-request没有缓存。但这只适用于从同一域加载的图像(或任何其他资源)作为页面(XMLHttpRequest限制)。

var xhr = new XMLHttpRequest();
xhr.open("POST", "url_for_image_file", true);
xhr.onreadystatechange = function() {
    if(xhr.readyState === 4)
      if(xhr.status!==200) {
        // no image loaded
        alert("fail connect to server");
      }
      else {
        alert("connection success");
      }
};
xhr.send(null);

检查互联网连接的完美解决方案是给您的服务器一个ajax调用虚拟页面,并使该虚拟页面的条目在网络部分的应用程序缓存清单文件中,以便它可能不会被缓存到浏览器中,否则它会从浏览器中获取该文件并显示您在线,即使您处于离线模式