Why is my JavaScript alert message displayed before an image is updated using document.getElementByID?

StackOverflow https://stackoverflow.com/questions/4026868

Question

In my JavaScript code I am first calling a function to update an image:

document.getElementByID("i1").src = newImage;

then a few statements later the alert() function is called to display a message:

alert("image updated!");

However, when I run this code, what actually happens is that the alert box is popped up before the image is updated. When I click the "OK" button in the dialog to take the alert box down, the image updates.

Why is the order of these events not being preserved? And is there some kind of synchronizing function I can call to wait for the image update to complete before the alert dialog is displayed?

I'm open to restructuring the code in some ways (i.e., using something other than the alert() function), but I'd prefer a solution that allows the existing code to work as intended.

Was it helpful?

Solution

Image loading is asynchronous. What you need is a callback for when the image is loaded.

If you are using jQuery, you can do it like this:

var img = $('#i1');
img.load(function() {
    alert('image updated!');
});
img.src = newImage;

If you are using Prototype, you can do it this way:

var img = $('i1');
Event.observe(img, 'load', function(e) {
    alert('image updated!');
});
img.src = newImage;

Note that in either case it's important that you first define the callback, then set the image src.

OTHER TIPS

Simple.

Setting the src property of the image initiates the loading of the image. But since the loading happens asynchroneously, the alert box displays before the loading completes.

The alert box blocks the updating of the image in the background. What the browser does is the downloading of the image (you can see this with wireshark or something similar) but the browser doesn't change anything on the web page while JavaScript is executed. If you have computationally intensive javascript methods, try using WebWorkers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top