你如何在 Javascript 中缓存图像 [英] How do you cache an image in Javascript

查看:68
本文介绍了你如何在 Javascript 中缓存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和我的朋友正在开发一个网站,我们希望在该网站上缓存某些图像,以便将来更快地显示它们.我有两个主要问题:

My friends and I are working on a website where we would like to cache certain images in order to display them faster in the future. I have two main questions:

  1. 如何缓存图像?
  2. 图片被缓存后如何使用?(只是为了验证,如果图像缓存在页面 A 上,可以从缓存中调用它以在页面 B 上使用它,对吗?)

另外,是否可以设置什么时候缓存的图像版本将过期?

Also, is it possible to set when the cached version of the image will expire?

如果包含一个示例和/或指向进一步描述此内容的页面的链接,我们将不胜感激.

It would be much appreciated if an example and/or a link to a page which describes this further was included.

我们可以使用原始 Javascript 或 jQuery 版本.

We're fine using either raw Javascript or the jQuery version.

推荐答案

一旦图像以任何方式加载到浏览器中,它就会在浏览器缓存中,并且下次使用时加载速度会更快,无论是使用在当前页面或任何其他页面中,只要该图像在浏览器缓存过期之前使用.

Once an image has been loaded in any way into the browser, it will be in the browser cache and will load much faster the next time it is used whether that use is in the current page or in any other page as long as the image is used before it expires from the browser cache.

因此,要预缓存图像,您要做的就是将它们加载到浏览器中.如果你想预缓存一堆图像,最好用 javascript 来做,因为当从 javascript 完成时它通常不会阻止页面加载.你可以这样做:

So, to precache images, all you have to do is load them into the browser. If you want to precache a bunch of images, it's probably best to do it with javascript as it generally won't hold up the page load when done from javascript. You can do that like this:

function preloadImages(array) {
    if (!preloadImages.list) {
        preloadImages.list = [];
    }
    var list = preloadImages.list;
    for (var i = 0; i < array.length; i++) {
        var img = new Image();
        img.onload = function() {
            var index = list.indexOf(this);
            if (index !== -1) {
                // remove image from the array once it's loaded
                // for memory consumption reasons
                list.splice(index, 1);
            }
        }
        list.push(img);
        img.src = array[i];
    }
}

preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"]);

可以根据需要多次调用此函数,并且每次只会将更多图像添加到预缓存中.

This function can be called as many times as you want and each time, it will just add more images to the precache.

一旦通过 javascript 像这样预加载图像,浏览器会将它们保存在其缓存中,您只需在其他地方(在您的网页中)引用普通 URL,浏览器将从其缓存中获取该 URL 而不是而不是通过网络.

Once images have been preloaded like this via javascript, the browser will have them in its cache and you can just refer to the normal URLs in other places (in your web pages) and the browser will fetch that URL from its cache rather than over the network.

最终,随着时间的推移,浏览器缓存可能会填满并丢弃一段时间未使用的最旧的东西.所以最终,图像将从缓存中清除,但它们应该在那里停留一段时间(取决于缓存有多大以及其他浏览完成了多少).每次实际再次预加载图像或在网页中使用图像时,它都会自动刷新它们在浏览器缓存中的位置,因此它们不太可能从缓存中刷新.

Eventually over time, the browser cache may fill up and toss the oldest things that haven't been used in awhile. So eventually, the images will get flushed out of the cache, but they should stay there for awhile (depending upon how large the cache is and how much other browsing is done). Everytime the images are actually preloaded again or used in a web page, it refreshes their position in the browser cache automatically so they are less likely to get flushed out of the cache.

浏览器缓存是跨页面的,因此它适用于加载到浏览器中的任何页面.因此,您可以在您网站的一个地方进行预缓存,然后浏览器缓存将适用于您网站上的所有其他页面.

The browser cache is cross-page so it works for any page loaded into the browser. So you can precache in one place in your site and the browser cache will then work for all the other pages on your site.

当如上预缓存时,图像是异步加载的,因此它们不会阻止页面的加载或显示.但是,如果您的页面有很多自己的图像,这些预缓存图像可能会与页面中显示的图像争夺带宽或连接.通常,这不是一个明显的问题,但在连接速度较慢的情况下,这种预缓存可能会减慢主页的加载速度.如果最后加载预加载图像是可以的,那么您可以使用该函数的一个版本,该版本会等到所有其他页面资源都已加载后才开始预加载.

When precaching as above, the images are loaded asynchronously so they will not block the loading or display of your page. But, if your page has lots of images of its own, these precache images can compete for bandwidth or connections with the images that are displayed in your page. Normally, this isn't a noticeable issue, but on a slow connection, this precaching could slow down the loading of the main page. If it was OK for preload images to be loaded last, then you could use a version of the function that would wait to start the preloading until after all other page resources were already loaded.

function preloadImages(array, waitForOtherResources, timeout) {
    var loaded = false, list = preloadImages.list, imgs = array.slice(0), t = timeout || 15*1000, timer;
    if (!preloadImages.list) {
        preloadImages.list = [];
    }
    if (!waitForOtherResources || document.readyState === 'complete') {
        loadNow();
    } else {
        window.addEventListener("load", function() {
            clearTimeout(timer);
            loadNow();
        });
        // in case window.addEventListener doesn't get called (sometimes some resource gets stuck)
        // then preload the images anyway after some timeout time
        timer = setTimeout(loadNow, t);
    }

    function loadNow() {
        if (!loaded) {
            loaded = true;
            for (var i = 0; i < imgs.length; i++) {
                var img = new Image();
                img.onload = img.onerror = img.onabort = function() {
                    var index = list.indexOf(this);
                    if (index !== -1) {
                        // remove image from the array once it's loaded
                        // for memory consumption reasons
                        list.splice(index, 1);
                    }
                }
                list.push(img);
                img.src = imgs[i];
            }
        }
    }
}

preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"], true);
preloadImages(["url99.jpg", "url98.jpg"], true);

这篇关于你如何在 Javascript 中缓存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆