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

查看:104
本文介绍了如何在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。

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天全站免登陆