使用Javascript加载和缓存图像,并了解HTTP状态码

Load and cache images with Javascript and know HTTP status code

本文关键字:了解 HTTP 状态 图像 Javascript 加载 缓存 使用      更新时间:2023-09-26

我正试图预加载图像以删除那些会响应404或500 HTTP状态码的图像。我需要知道什么是HTTP状态码我需要缓存的图像。我的问题是:

  1. 如果我使用Image或假<img/>标签,图像被缓存,但我无法知道onerror回调中的HTTP状态代码。
  2. 如果我使用XHR ($.get for jQuery或$http.get for angular),我得到状态代码,但图像没有缓存(真正的<img/>将再次加载数据)。我想我没有控制缓存,因为这是浏览器规则。

是否有一种方法可以使HTTP状态码和图像缓存由浏览器?

通过让onerror触发请求以获取更多详细信息来使用两者的组合

var img= document.createElement('img');
img.src="....";
img.onerror = function(err){
   $.get(img.src).fail(xhr){
        //parse xhr details and do something with them      
   })
}

注意,这将受到跨域源的CORS限制

或者如果是在赋值给image元素的指令中:

 link:function(scope, element){
    element[0].onerror = function(err){
       $.get(element[0].src).fail(xhr){
          //parse xhr details and do something with them      
       })
    }
 }