如何给图片做缓存

在大型网页中,我们会遇到一张大图片需要被下载下来,但是要考虑到图片下载下来的时间会阻塞其他资源的下载,为了有效得控制住图片所占用的网络资源,可以使用javascript方式来解决这个问题,大概代码是这样的:

 1 function preloadImages(array) {
 2     if (!preloadImages.list) {
 3         preloadImages.list = [];
 4     }
 5     for (var i = 0; i < array.length; i++) {
 6         var img = new Image();
 7         img.onload = function() {
 8             var index = preloadImages.list.indexOf(this);
 9             if (index !== -1) {
10                 // remove this one from the array once it's loaded
11                 // for memory consumption reasons
12                 preloadImages.splice(index, 1);
13             }
14         }
15         preloadImages.list.push(img);
16         img.src = array[i];
17     }
18 }
19 
20 preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"]);

我们可以看得出来,这是对需要加载的图片进行预加载,但是这样就能够缓存图片吗,不是的,这只是给图片进行预加载,并不能算是缓存图片,当图片加载到网页中的时候,浏览器会对这些资源进行缓存,在第二次加载的时候不会重新请求服务器,它会预先加载缓存的文件

原文地址:https://www.cnblogs.com/lenq/p/4076987.html