获取图片不包含再次下载

Iam using yii framework. i have created a function/controller which check the image file is exist in the directory, if file is exists using file_get_contents() function pass the image and set the background of the div tag. If file is not exists the default image file contain is passing.

syntax php:-

  header('Content-Type: image/png');
  echo file_get_contents($location); 

And in javascript i create a function to draw adiv and set background of that div Syntax:-

 function drawDiv()
{
$('.divID').html("<div id="test"></div>")
$('#test').css({background-image : url('http://location/test/getimage')});
}

when ever i redraw the div again the image is download every time. if i set the url absolute path it download once.

what i want is that if the image is exist or not exist the should download once. plz solve issue.. if you have another solution tell me.

I would use clone. From a quick test, the image isn't redownloaded. (See screengrab at the bottom, or open your network panel and test)

Implementation

So, you could have #test set up (with the background image, and styling you want), but hidden. And just clone() it whenever you want.

<div id="test" style="background-image:url(http://location/test/getimage);display:none;">
</div>

And your Javascript would be

$("#test").clone().show().prependTo("body");

Try the jsFiddle

  • Notice the image is only downloaded once (open your network panel, and see)

Code test

$( "img" ).clone().prependTo( "body" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://www.google.co.uk//images/srpr/logo11w.png" />

enter image description here

</div>