Upload and cache images using Javascript and know the HTTP status code

I am trying to preload images to remove those that will respond with a 404 or 500 HTTP status code. I need to know what the HTTP status code is and I need the image to be cached . Here is my problem:

  • If I use a tag Imageor dummy <img/>, the image is cached, but I cannot recognize the HTTP status code in the callback onerror.
  • If I use XHR ( $.getfor jQuery or $http.getfor angular), I get a status code, but the image is not cached (the real one <img/>will load the data again). I think I have no control over caching, as this is a browser rule.

Is there a method that allows you to have an HTTP status code and image caching by the browser ?

+4
source share
1 answer

Use a combination of the two: onerrorrun a query for more details

var img= document.createElement('img');
img.src="....";

img.onerror = function(err){
   $.get(img.src).fail(xhr){
        //parse xhr details and do something with them      
   })
}

Note. At the same time, CORS restrictions for cross-domain sources will obey

Or, if specified in a directive assigned to an image element:

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

Source: https://habr.com/ru/post/1657630/


All Articles