How to cache image in 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:

  • How to cache an image?
  • How do you use the image after caching? (and just to check if the image is cached on page A, you can call it from the cache to use it on page B, right?)

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

It would be very useful if an example and / or link to the page that describes this further would be given.

We make good use of either raw Javascript or a jQuery version.

+47
javascript jquery caching image browser-cache
Apr 20 2018-12-12T00:
source share
8 answers

As soon as the image is somehow loaded into the browser, it will be in the browser’s cache and will load much faster the next time it is used, whether on the current page or on any other page, while the image is used before its expiration from the browser cache.

Thus, to preview the images, all you have to do is upload them to your browser. If you want to precedent a bunch of images, it is probably best to do this with javascript, as it usually will not hold the page loading when executed with javascript. You can do it 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 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 simply adds more images to the archive file.

Once the images have been preloaded using javascript, the browser will have them in its cache, and you can just link to ordinary URLs in other places (on your web pages), and the browser will extract this URL from its cache, than over the network.

Over time, the browser cache can fill and throw the oldest things that have not been used for some time. Thus, the images will be unloaded from the cache, but they should remain there for a while (depending on how large the cache is and how many other browsers are made). Each time the images are actually preloaded or used on a web page, it automatically updates its position in the browser cache, so they are less likely to exit the cache.

The browser cache is a cross page, so it works for any page loaded in the browser. Thus, you can perform a preliminary check in one place on your site, and the browser cache will work for all other pages on your site.




With preliminary preparation, as shown above, images are loaded asynchronously, so they will not block the loading or display of your page. But, if your page has many native images, these precache images may compete for the bandwidth or connection with the images displayed on your page. This is usually not a noticeable problem, but with a slow connection this preliminary preparation can slow down the loading of the main page. If it were normal to load preload images, then you could use a version of the function that will wait to start preloading until all other page resources are 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 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); 
+88
Apr 20 '12 at 4:30
source share

since @Pointy said you are not caching images using javascript, the browser does this. so it may be what you ask for, or it may not be ... but you can preload the images using javascript. Having placed all the images that you want to preload into the array, and placing all the images in this array into hidden img elements, you efficiently load (or cache) the images.

 var images = [ '/path/to/image1.png', '/path/to/image2.png' ]; $(images).each(function() { var image = $('<img />').attr('src', this); }); 
+10
Apr 20 '12 at 4:13
source share

There are a few things you can pay attention to:

Image preload
Setting cache time in .htaccess file
The size of the image files and base64 encoding them.

Preload: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Caching: http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html

There are a few different thoughts for base64 encoding, some say that HTTP requests link bandwidth, while others say that “perceived” downloads are better. I will leave it in the air.

+2
Apr 20 '12 at 4:13
source share

I have a similar answer for asynchronously preloading images via JS. Downloading them dynamically is the same as loading them in normal mode. they will cache.

as for caching, you cannot control the browser, but you can install it through the server. if you need to load a really fresh resource on demand, you can use the cache caching method to force a new resource to load.

+1
Apr 20 '12 at 4:18
source share

Even if your question says “using javascript,” you can use the prefetch attribute of the link tag to preload any asset. At the time of this writing (August 10, 2016), it is not supported in Safari, but almost everywhere:

<link rel="prefetch" href="(url)">

More about support here: http://caniuse.com/#search=prefetch

Please note that IE 9.10 is not listed in the caniuse matrix because Microsoft has stopped supporting them.

So, if you are really stuck with using javascript, you can use jquery to dynamically add these elements to your page; -)

+1
Aug 10 '16 at 12:39
source share

I use a similar method for lazyload images, but I can not help but notice that Javascript does not have access to the browser cache on first boot.

My example:

I have a rotating banner on my homepage with 4 images that are waiting for sliders for 2 seconds, than javascript loads the next image, waits 2 seconds, etc.

These images have unique URLs that change when I change them, so they get caching headers that will be cached in the browser for a year.

 max-age: 31536000, public 

Now, when I open Chrome Devtools and make sure that the "Disable cache" option is not active and loads the page for the first time (after clearing the cache), all images are fetched and have a status of 200. After a full cycle of all images in the banner, network requests stop and cached images are used.

Now when I do a regular update or go to a subpage and click back, the images that are in the cache seem to be ignored. I expect to see a gray disc-cache message on the Network tab in Chrome devtools. Instead, I see that requests go through every two seconds with a green status circle rather than gray, I see that the data is being transmitted, so I get the impression that the cache is not accessible at all from javascript. It just extracts the image every time the page loads.

Thus, each request to the main page starts 4 requests regardless of the image caching policy.

Given the above and the new http2 standard, which supports most web servers and browsers, I think it's better to stop using lazyloading, since http2 will download all images almost simultaneously.

If this is a bug in Chrome Devtools, it really is surprising that no one has noticed it yet.;)

If this is true, using lazyloading only increases bandwidth usage.

Please correct me if I am wrong. :)

+1
Mar 07 '17 at 17:04 on
source share

Yes, the browser automatically caches images for you.

However, you can set the expiration of the image cache. Check this question and answer the stack overflow question:

Duration of cache on static images

0
Apr 20 '12 at 4:15
source share

I always prefer to use the example mentioned in Konva JS: Image Events for Image Upload.

  • You should have a list of image URLs as an object or an array, for example:

    var sources = { lion: '/assets/lion.png', monkey: '/assets/monkey.png' };

  • Define the definition of the function in which it receives the list of image URLs and the callback function in the list of its arguments, so when it finishes loading the image, you can start the shutdown on your web page:

  function loadImages(sources, callback) { var images = {}; var loadedImages = 0; var numImages = 0; for (var src in sources) { numImages++; } for (var src in sources) { images[src] = new Image(); images[src].onload = function () { if (++loadedImages >= numImages) { callback(images); } }; images[src].src = sources[src]; } } 
  1. Finally, you need to call the function. You can call it, for example, from jQuery. Ready for the document.

$(document).ready(function (){ loadImages(sources, buildStage); });

0
Aug 28 '17 at 7:56 on
source share



All Articles