I'm lazyloading images through a custom XMLHttpRequest
(there's nothing unusual in it so, to help this question remain legible, I'll omit most of it unless the issue isn't obvious without it. It's pretty much like the following example).
I look through the data-srcset
of each img
element for the most appropriate size, preload it, then place it as a src
attribute in the appropriate img
element. The img
elements look like the following, before preloading:
<img class='img img__lazyload'
data-srcset="/images/400/1473091018.jpg 400w,
/images/1400/1473091018.jpg 1400w,
/images/1800/1473091018.jpg 1800w">
Everything works fine. My issue is that I am not well set up for good caching practices as the image blob
I create is placed as the src
of the element, of course, rather than the real url to the actual location of where the image was sourced from. So instead of:
src="blob:http://example.com/2f3e365d-be2d-47ca-ba72-dceb5552adc5"
I would like the src
to be something like this instead:
src="/images/1400/1473091018.jpg"
so that the browser can realise it already has the image cached (if so) and use that, rather than seeing a blob that's unique and loading the image each time the site is visited, despite having loaded it previously. The problem is, I'm not sure how to go about this as I'm only familiar with creating an image blob
like so:
xmlHTTP.onload = function (e) {
var blob = new Blob([this.response]);
thisImg.src = window.URL.createObjectURL(blob);
};
I create the src
in the img
element by replacing the entire element with my image
object like so (as well as copying the attributes of the original over):
var img = new Image(); // creates a new image object which includes the above onload function
$('.img-container').eq(index).find('img').replaceWith(img);
I'm guessing I can't avoid using a blob
if using an XMLHttpRequest
, but my attempts to compare this to the source of the file have proved fruitless so far. I'm using XMLHttpRequest
to provide feedback to a progress bar as the image loads for a slideshow.
Update
I've been developing with caching turned off and just assumed that, as the url of src
showed a temporary, unique blob
url, that it would prevent any form of caching.
Am I imagining, now that I've tried turning caching back on, that the browser does cache the images relative to their original source url? As in, even though I've got blob
showing as the src
, that because it was retrieved originally from http://example.com/....
that the browser will recognise that it has the image in its cache?