Reputation: 865
if after rendering page i change src of an img tag from javascript like:
function changeImage(){
img.src = 'getImage?imgId=232132'; //getImage is calling doGet() Method of Servlet with response content type "image/jpeg"
}
is this make asynchronous call and load image or not?
Upvotes: 0
Views: 1474
Reputation: 972
Please set your header of your file. if you use php, try this:
<?php
header("Content-type: image/jpeg");
?>
Good luck
Upvotes: -1
Reputation: 11908
The simplest answer is yes, it will happen asynchronously. However, there is a little more to it.
The idea is that what you do during the javascript is only modify the model (DOM) of the page that it should display. The browser will have to make sure that the page is rendered according to the new specifications in the model and basically and in this case that includes downloading an image. However, the way your browser does this rendering is left up to the browser, though it shouldn't ever block your javascript.
In fact, the way I have seen a number of major browsers handle the case your are describing is that indeed there would be an asynchronous request for the image, but not until after your javascript is done running. In other words, if you were to follow it up with a busy wait (while (true) {}
) the image wouldn't get loaded at all. However, if you are to set a timeout event for a second after changing the src
of the image, the page would have interpreted the new src and done the asynchronous request for the image, but there is no guarantee whether the image has finished loading or not by the time that second has passed. However, other browsers may do this differently and it's best not to rely on any behavior other than the behavior you know to be true (that it won't block your javascript and that if you want to do something once you are done loading, you should use the appropriate DOM even).
Upvotes: 1
Reputation: 382102
Yes, the call is asynchronous, except if it's not really a distant call because the image is in cache (in this case, the image will be loaded before the next line of the script is executed).
If you want to be notified when it's finished, do this :
img.onload = function(){alert('loaded!')};
img.src = 'getImage?imgId=232132';
Upvotes: 2
Reputation: 943207
Yes. No loading of content triggered by DOM modification will block JavaScript.
Upvotes: 2