Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for image to load in JavaScript

I'm making an Ajax call which returns me some info including an image path.

I prepare all this information in my HTML which will be displayed as a kind of popup. I just toggle the visibility of by popup div from hidden to visible.

To set the position of my popup div, I have to calculate depending on the height of the image. So, I have to wait for the image to load to know its dimension before setting position and switching visibility to visible.

I tried tricks with recursion, setTimeout, complete img property, while loop... without success.

So, how can I do this? Maybe I should return dimensions in my Ajax call.

like image 486
Jeenyus Avatar asked Feb 26 '10 14:02

Jeenyus


People also ask

How to wait for images to load in js?

The onload event on window does wait for images to be loaded, but only for the initial page load. In the context of this question, the onload event should be tied directly to the image element that is being loaded instead.

How do you check if all images are loaded in jQuery?

To check if an image is loaded successful or not, you can combine the use of jQuery 'load()' and 'error()' event : $('#image1') . load(function(){ $('#result1'). text('Image is loaded!


1 Answers

var img = new Image(); img.onload = function() { alert("Height: " + this.height); } img.src = "http://path/to/image.jpg"; 

Note that it's important to do it in the order above: First attach the handler, then set the src. If you do it the other way around, and the image is in cache, you may miss the event. JavaScript is run on a single thread in browsers (unless you're using web workers), but browsers are not single-threaded. It's perfectly valid for the browser to see the src, identify the resource is available, load it, trigger the event, look at the element to see if it has any handlers that need to be queued for callback, not see any, and complete the event processing, all between the src line and the line attaching the handler. (The callbacks wouldn't happen between the lines if they were registered, they'd wait in the queue, but if there aren't any, the event isn't required to wait.)

like image 86
Josh Stodola Avatar answered Oct 18 '22 23:10

Josh Stodola