LapisSea LapisSea - 1 year ago 69
Javascript Question

JavaScript: How to check if image or any asset is stored by the browser and not downloaded from the internet

So I am loading some images with JavaScript (aka setting image src) and I am playing an animation on load.

But the problem is that I don't want it to play if it is already stored by the browser on the client. Why? Because pretty multiple images are instantly loaded and animated at the same time so that looks really bad/annoying.

So I would fix that by detecting if an asset (image) is already downloaded/stored or or there is a need to update the asset. This is where I got stuck.



width: 100%;
max-width: 0px;
transition: max-width 0.2s;
transition-timing-function: cubic-bezier(0.68, 0.12, 0.32, 0.85);



function imageClientStored(image){

Is there maybe a map with stored assets sorted with urls as keys or something like that?

Answer Source

If it was coming from an external source it should take some time to download. Check to see its load time, and if it takes too long, then it was most likely not local.

You can see it at work here. The first time you run this snippet, it should say "from web", the second time it should say "from cache".

//string url
//function local (for callback)
//function download (for callback)
function loadImage(url,local,download){
  var img = new Image();
  var start = new Date();
  img.onload = function(){
    if((new Date)-start > 25){//25ms elapsed;//binds this to img in download callback
    }else{;//binds this to img in local callback
  img.src = url;
  return img;
var testImg = loadImage(
    function(){ console.log('from cache'); },
    function(){ console.log('from web'); }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download