Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  175] [ 1]  / answers: 1 / hits: 31862  / 11 Years ago, fri, april 12, 2013, 12:00:00

What is the best way to use the jQuery load function synchronously.



I need to load an image but can't execute the next line of code until that image has loaded.



I could loop a variable until the load has completed but was wondering if there was a better way of doing that.



var img = jQuery('<img src=' + url + '/>').load(function () {                 

});
//Run code here once img load has comlpeted.

More From » jquery

 Answers
60

From what I know, the load event will always fire asynchronously, except if the image is already cached (in some browsers). The only reliable solution is to put the code in a callback like you did. However, to make sure the load handler will always be fired in all browsers, even if the image is cached, make sure to add the handler before setting the src property of the image.


[#78946] Thursday, April 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
cadendericki questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Wed, Jul 8, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;