javascript - image on html - cache -


i have web page, has image. image loaded seconds after page opens. want display loading gif while image has not been loaded, , check if image has been loaded every 2 seconds. once image has been loaded, want replace loading gif image. i've written following code:

    <script language="javascript" type="text/javascript">         function checkimage(src) {             var img = new image();             img.onload = function () {                 // code set src on success                 $('#img1').attr('src', 'imageoriginal.jpg');                 $('#img1').removeattr('width');                 clearinterval(interval);             };             img.onerror = function () {                 counterrors = counterrors + 1;             };              img.src = src; // fires off loading of image         }         var interval;         var counterrors = 0;         $(document).ready(function () {             $('#img1').attr('width', '620px');             interval = window.setinterval(function () { checkimage('imageoriginal.jpg?id=' + counterrors); }, 2000);         });     </script>                  <img borderstyle="solid" bordercolor="black" borderwidth="1px" id="img1" alt="screenshot" style="max-width:620px;" src="loading.gif" /> 

it works, , don't. added id parameter prevent caching. loading gif shown if image has loaded. how solve this?

if jquery involved in script, 1 way i've seen done attaching onload event image, similar have there, except onload event triggers when image in fact loaded. upon event hide loading image. think make more sense have loading image own separate image , hide/show depending on whether main image loaded or not.

example:

$('#img1').load(function() {     $('#loadingimage').hide();     $('#img1').show(); }); 

no need have check on interval. load event needs attached once , fire reliably when image finishes loading.


Comments