Reputation: 26766
I've got a rudimentary remote control API for a PC which accepts commands via AJAX (Move mouse, click, send key, etc.) It also serves images for the specified screen
The API has a front-end which is mostly jQuery-powered.
I have an img
tag which shows the currently selected screen's screenshot and has mouse move/click events which call the appropriate APIs behind the scenes.
The screen image is currently updated like this:
function UpdateScreen() {
$("#Screenshot").attr("src", "./AJAX/UI/GetScreen.aspx?Screen=" + encodeURIComponent(targetScreen) + "&Date=" + encodeURIComponent(Date()));
setTimeout('UpdateScreen()', 3000);
}
Which works ok but is ridiculously inefficient - Either the image loads in less than 3 seconds in which case, my refresh rate is lower than it should be or in more than 3 second in which case the old request is terminated (eg mobile over 2G).
How can I reload an image as soon as it finishes loading? Even better, is there any way I can do it in the same way as an AJAX call rather than relying on the browser? That way, I can catch failures, have a progress bar and also control how the image redraws (using something like a back-buffer).
Thanks in advance
Upvotes: 0
Views: 661
Reputation: 490163
Try this...
function UpdateScreen() {
var imgSrc = "./AJAX/UI/GetScreen.aspx?Screen=" + encodeURIComponent(targetScreen) + "&Date=" + encodeURIComponent(Date()),
img = new Image();
img.onload = function() {
$("#Screenshot").attr("src", img.src );
setTimeout(UpdateScreen, 3000);
};
img.src = imgSrc;
}
Upvotes: 1
Reputation: 82903
Use the load event on the image. i.e:
$("#Screenshot").load(UpdateScreen);
function UpdateScreen(){
$("#Screenshot").attr("src", "./AJAX/UI/GetScreen.aspx?Screen="
+ encodeURIComponent(targetScreen) + "&Date=" + encodeURIComponent(Date()));
}
Upvotes: 1
Reputation: 82483
Use the native Javascript Image
object and wait for onload to fire before setting the timeout...
function UpdateScreen() {
var img = new Image();
img.onload = function() {
$("#Screenshot").attr("src", this.src);
setTimeout(UpdateScreen, 3000);
}
img.src = "./AJAX/UI/GetScreen.aspx?Screen=" + encodeURIComponent(targetScreen) + "&Date=" + encodeURIComponent(new Date());
}
Upvotes: 2