web部署-JavaScript:如何检查图像或任何资产是否由浏览器存储,而不是从互联网下载

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

本文关键字:存储 浏览器 是否 下载 互联网 任何资 何检查 -JavaScript 部署 图像 检查      更新时间:2023-09-26

所以我正在用JavaScript加载一些图像(也称为设置图像src),并在加载时播放动画。

但问题是,如果浏览器已经将其存储在客户端上,我不希望它播放。为什么?因为相当多的图像会立即加载并同时设置动画,所以看起来真的很糟糕/令人讨厌。

因此,我会通过检测资产(图像)是否已经下载/存储,或者是否需要更新资产来解决这个问题。这就是我被卡住的地方。

示例:

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){
    ??????????
}

是否有一个地图,其中存储的资产以url作为关键字或类似的东西进行排序?

如果它来自外部源,下载应该需要一些时间。检查它的加载时间,如果时间太长,那么它很可能不是本地的。

你可以在这里看到它的工作。第一次运行这个片段时,它应该说"来自web",第二次应该说"从缓存"。

//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'); }
);