LapisSea LapisSea - 4 months ago 8
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.

Example:

CSS:

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


JavaScript:

image.onload=function(){
if(imageClientStored(this)){
this.style.transition="";
this.style.max-width="100%";
}
else this.style.max-width="100%";
}
image.src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150";

function imageClientStored(image){
??????????
}


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

Answer

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".

//expects
//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
      download.call(img);//binds this to img in download callback
    }else{
      local.call(img);//binds this to img in local callback
    }
  };
  img.src = url;
  return img;
}
  
var testImg = loadImage(
    "https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150",
    function(){ console.log('from cache'); },
    function(){ console.log('from web'); }
);
  

Comments