6

I'm using TimThumb which is a PHP script for resizing images.

It caches the image, and my web application relies on that caching to operate properly.

When the image is not cached on the server, it doesn't work right, I'm wondering if there's a way to force timthumb to cache an image, and then retrieve it, or if there's a way to use JavaScript to ensure the image gets cached first.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Adola
  • 588
  • 7
  • 21
  • possible duplicate of [How do you cache an image in Javascript](http://stackoverflow.com/questions/10240110/how-do-you-cache-an-image-in-javascript) – Lix Jul 28 '12 at 11:54

1 Answers1

1

To ensure the browser preloads an image into cache, you can use some native JavaScript objects.

var imgPreload = new Image();
imgPreload.src = PATH_TO_IMAGE;

Now when you give an <img> tag an src attribute that's the same as PATH_TO_IMAGE, it'll already have been preloaded by the browser.

<img src="PATH_TO_IMAGE" width="100%" >

You could also load some images into your HTML and simply use some css trickery to hide them -

  • display:none

    or

  • visibility:hidden

then only display them when they are fully loaded. You could use the .load() function for that. Just attach it to the <img> tag -

$("#imageSelector").load(function(){
  // image was fully loaded.
});
Community
  • 1
  • 1
Lix
  • 47,311
  • 12
  • 103
  • 131
  • I'm unsure of how to utilize this html object. Do I use the variable `imgPreload` just as if I'd use `` ? – Adola Jul 28 '12 at 00:11
  • The idea is when you come to display that image - it will have already been loaded by those two lines of code. – Lix Jul 28 '12 at 00:13
  • Right, but I can't find any documentation on Image(); I'm returning a string with my html elements, and when I include `imgPreload`, it returns `[[object HTMLImageElement]]` – Adola Jul 28 '12 at 00:18
  • 1
    nvm, you have to use `''` – Adola Jul 28 '12 at 00:25
  • @ado - yea, sorry, I forgot to explain that you really don't have to do anything more than execute those two lines of code. The image will be loaded from the same URL if you use `imgPreload.src` or even explicitly pass the direct URL to the image file. – Lix Jul 28 '12 at 11:52