How do I pre-cache images for quick viewing with javascript?

Asked
Active3 hr before
Viewed126 times

8 Answers

cachejavascriptimages
90%

You don't need to create any page elements, it can all be preloaded using JavaScript:,That said, ALassek's suggestion of using CSS sprites is an excellent one, if you have scope to do it. The advantages of sprites are many: fewer HTTP requests, smaller download size (usually), works without JavaScript enabled.,If I understand your case correctly you still need javascript, but you can "preload" image this way nevertheless. ,Connect and share knowledge within a single location that is structured and easy to search.

You don't need to create any page elements, it can all be preloaded using JavaScript:

tempImg = new Image()
tempImg.src = "pic2.jpg"

If you have a lot of images, you can use the poor-man's multi-preloader:

preloads = "red.gif,green.gif,blue.gif".split(",")
var tempImg = []

for (var x = 0; x < preloads.length; x++) {
   tempImg[x] = new Image()
   tempImg[x].src = preloads[x]
}
load more v
88%

I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map.,Then, when moused over, the browser will already have that image in its cache and will switch it over very fast.,Doing this with sprites is a good solution, because you don't have to wait to load the new image. Sprites work by combining the two images into one, and changing the background offset on mouseover.,Use display: none;, then have the Javascript change it to display: inline when you want to display it. This has the added advantage of being able to put the image exactly where you want in the page's source, rather than having to add it with Javascript later.

I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map.

<img src="pic.jpg" usemap="#picmap" />
<map id="picmap" name="picmap"><area shape="rect" coords="10,20,30,40" onMouseOver="mouse_on_write('mouse is on spot')" onMouseOut="mouse_off('mouse is off spot')" href="http://www....html" target="_blank" />
</map>
<p id="desc"></p>

Where in the header I defined these functions:

 <script type="text/javascript">
 function mouse_off(txt)
    {
    document.getElementById("desc").innerHTML=txt;
    document.p1.src="pic.jpg";
    }
 function mouse_on_write(txt)
    {
    document.getElementById("desc").innerHTML=txt;
    document.p1.src="pic2.jpg";
  </script>
load more v
72%

Preloading Images with CSS and JavaScript,Pure CSS: Better Image Preloading without JavaScript,CSS Throwdown: Preload Images without JavaScript,A Way to Preload Images without JavaScript that is SO Much Better

With that method, images are easily and effectively preloaded using the following CSS:

#preload - 01 {
      background: url(http: //domain.tld/image-01.png) no-repeat -9999px -9999px; }
            #preload - 02 {
               background: url(http: //domain.tld/image-02.png) no-repeat -9999px -9999px; }
                     #preload - 03 {
                        background: url(http: //domain.tld/image-03.png) no-repeat -9999px -9999px; }
load more v
65%

Image Preloading using HTML5, CSS, and JavaScript,You may have to also employ a bit of trickery such as setting the visibility to hidden and or position elements off-screen.,We can use preload to load images ahead of time, along with the media attribute in order to restrict the downloading of an image to devices of a certain resolution:,CSS has been a viable way to preload images ever since the inclusion of the background-image attribute. Since then CSS2 and CSS3 have continued to add ever more options.

Let’s begin with the most established one. It sets the rel attribute to “prefetch”, using the following basic format:

<link rel="prefetch" href="(url)">
load more v
75%

We can compare the download sequence and times on a simulated 2Mbps connection using Chrome’s development tools:,The canonical javascript image preloader attempts to maximize the browser’s ability to load resources in parallel. While this is a good strategy for certain resources, it is not necessarily the best strategy for loading a gallery full of high resolution images, especially if you can predict user behavior.,(Simulated 2Mbps connection — total time: 25.44 seconds. larger version ),(Simulated 2Mbps connection — total time: 24.01 seconds. larger version )

An informal survey on the web (for example) reveals what appears to be a consensus on the canonical way to preload a set of images. In its simplest form it looks something like this:

/* 'images' is an array with image metadata including a 'url' property */
for (var i = 0; i < images.length; ++i) {
   var img = new Image();
   img.src = images[‘url’];
}
load more v
40%

Depending on your site's structure, that could mean significantly faster image display! We ran tests on a site that uses JavaScript to lazy-load responsive images. Preloading resulted in images loading 1.2 seconds faster.,You can inspect this issue on a website with a dynamically-loaded image gallery:,You can inspect this issue on an example website with responsive background image.,Of course, nothing captures the visual difference quite like a filmstrip comparison:

<img src="small.jpg" srcset="small.jpg 500w, medium.jpg 1000w, large.jpg 1500w" alt="…">
load more v
22%

On mouse move over a button in normal state, it changes to hover state. On mouse out, it goes back to normal state. ,The preloadImages() function takes care of loading all the images into the cache, so that response time on mouse movement is minimal. A for() loop is used to iterate over the images created in the first step and preload each one.,In practice, you will probably need to preload more than just one image; for example, in a menu bar containing multiple image rollovers, or if you're trying to create a smooth animation effect. This is not difficult; all you need to do is make use of JavaScript's arrays, as in the example below:, Ethics policy: Vendor relationships

The simplest way to preload an image is to instantiate a new Image() object in JavaScript and pass it the URL of the image you want preloaded. Say we have an image called heavyimagefile.jpg, which we want to display when the user mouses over an already-displayed image. In order to preload this image for faster response time, we simply create a new Image() object, called heavyImage, and load it simultaneously to the page with the onLoad() event handler:

<html>
<head>
<script language = "JavaScript">
function preloader() 
{
heavyImage = new Image(); 
heavyImage.src = "heavyimagefile.jpg";
}
</script>
</head>
<body onLoad="javascript:preloader()">
<a href="#" onMouseOver="javascript:document.img01.src='heavyimagefile.jpg'">
<img name="img01" src="justanotherfile.jpg"></a>
</body>
</html>
load more v
60%

I have a webpage where I want the user to see a new image when they hover over a specific part of the image. I used an image map.,Doing this with sprites is a good solution because you don't have to wait for a new image to load. Sprites work by combining two images into one and changing the background offset when you hover over the mouse.,Then, when it is obscured, the browser will already have this image in its cache and will switch it very quickly.,Use display: none; then Javascript change it to display: inline when you want to display it. This has the added benefit that you can place the image exactly where you want in the page source, instead of adding it using Javascript later.

I have a webpage where I want the user to see a new image when they hover over a specific part of the image. I used an image map.

<img src="pic.jpg" usemap="#picmap" /> <map id="picmap" name="picmap"><area shape="rect" coords="10,20,30,40" onMouseOver="mouse_on_write('mouse is on spot')" onMouseOut="mouse_off('mouse is off spot')" href="http://www....html" target="_blank" /> </map>
<p id="desc"></p>

Where in the header I defined these functions:

  <script type="text/javascript"> function mouse_off(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic.jpg"; } function mouse_on_write(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic2.jpg"; </script> 
load more v

Other "cache-javascript" queries related to "How do I pre-cache images for quick viewing with javascript?"