Using image.complete to find if the image will be cached to chrome?

I tried to find out if the external image is cached in the browser using js, this is the code that I still have:

<html> <head></head> <body> <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script> function cached( url ) { $("#imgx").attr({"src":url}); if(document.getElementById("imgx").complete) { return true; } else { if( document.getElementById("imgx").width > 0 ) return true; } return false; } </script> <img id="imgx" src="" /> <script> $(document).ready(function(){ alert(cached("http://www.google.com/images/srpr/nav_logo80.png")); }); </script> </body> </html> 

It works fine on firefox, but always returns false on chrome.

Does anyone know how to make it work with chrome?

+6
source share
1 answer

I rewrote your code in simple JavaScript to make it more jQuery independent. The core functionality has not changed. Fiddle: http://jsfiddle.net/EmjQG/2/

 function cached(url){ var test = document.createElement("img"); test.src = url; return test.complete || test.width+test.height > 0; } var base_url = "http://www.google.com/images/srpr/nav_logo80.png" alert("Expected: true or false\n" + cached(base_url) + "\n\nExpected: false (cache-busting enabled)\n" + cached(base_url + "?" + new Date().getTime())); //false = not cached, true = cached 

The first time I get false and false . After I run the code again, I get true and false .


Using .complete and .height + .width gives the expected results (FF 3.6.23, Chromium 14).

Most likely, you have disabled caching in the Chrome browser. If not, check the HTTP headers of your displayed image (is Cache-control present?). This title exists in the Google sample.

If you want to detect when the image has finished loading, check out this question .

+13
source

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


All Articles