Have you also considered base64? For example, Display PNG image as response to jQuery AJAX request
On PHP:
<?php
$img = file_get_contents('someimage.png');
$imb64 = base64_encode($img);
header('Content-Type: image/png');
echo $imb64;
exit;
?>
On Javascript:
$.ajax({
type: "POST",
url:'myimage.php',
contentType: "image/png",
data: {},
success: function(data){
$('#myimage').css('background-image', 'url(' + 'data:image/png;base64,' + data+ ')');
}
});
Of course you need to change the above, its just a simple example.? Not tested as wrote/modified it to base basics
Of course you dont need to use jquery, this is just to shorten the example.. You should be able to use your xhr
Resources:
https://en.wikipedia.org/wiki/Data_URI_scheme
https://css-tricks.com/data-uris/
This method can be very handy, allows you to control hot-linking and show place holders for missing files along with the ability to control cache with a e-tag...
----------Im feeling nice-------------
function cacheByModified($file) {
if ($GLOBALS['VTIS']['cache']!==false) {
$ts = filemtime($file);
$gmt_mtime = gmdate('r', $ts);
header('ETag: "'.md5($ts.$file).'"');
header('Last-Modified: '.$gmt_mtime);
header('Cache-Control: public');
// IF HAS HEADERS
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $gmt_mtime || str_replace('"', '', stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])) == md5($ts.$file)) {
header('HTTP/1.1 304 Not Modified');
if (extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler")) {
ini_set("zlib.output_compression", 1);
}
exit;
}
}
}
}
// Cacher.. send normal headers, check if found.. if are.. return 304 and exit.
cacheByModified("filename.ext or some other unique id here per file..");
// Enable gzip before sending the file
if (extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler")) {
ini_set("zlib.output_compression", 1);
}
// Obtain the file itself
$img = file_get_contents('someimage.png');
$imb64 = base64_encode($img);
// Send main header and output
header('Content-Type: image/png']);
echo $imb64;
exit;
The above / attached code is a quick extract of my cache function, i've not tested it out side of the project as only doing this quick.. But should work if i am not mistaken.