Wednesday, December 10, 2014

JavaScript/jQuery: Caching Images

A neat image can say a lot of words, rather than using the words themselves.
Nice opening.
We can use CSS image sprites for small thumbnails, icons and other below 100px images. Therefore, minimizing the HTTP requests for a particular page.
But sometimes, there's that blank moment before the image resource is fully retrieved. Late, sort of speak.

To reduce the blankness period, we can cache the image object (source) as JavaScript/jQuery object.


JavaScript snippets
These are anonymous self invoked functions. You can further tinker it to suit your needs.
Change the URL with your actual image URL.

One image
Updated June 5, 2015


Multiple images
Updated June 5, 2015


Shorter version (with forEach() loop method)
Added June 5, 2015



jQuery snippets
One image
Updated June 5, 2015


Multiple images
Updated June 5, 2015



As you can see in those snippets, we're creating the img objects plus the src attribute, but not appending any of them to the HTML document.
That's the caching method.

This will be useful for page which has:
  • CSS background-image.
  • Hidden image(s) which will be shown with some triggers on one page.
  • "Future" images which exist on your other page, which is "very" linked to [this] page.
  • Photos/images slideshow thingy.

Those snippets can be placed in the head section or just above the closing </body> section. I'd recommend to place it on the bottom of the body section. The second option.
Each will be executed asynchronously. It won't block page rendering.

Use it with strategy. You don't want to burden your visitor by caching ALL images of your site to their browser. Pick your essential image resources.

Also, we can bind the onload event to each of the image for our custom callback function(s) trigger.

Hm.

That is all.


Link
Is there a difference between new Image() and document.createElement('img')? Disussion at Stack Overflow

No comments:

Post a Comment

Tell me what you think...