Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .load(function) synchronous

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.                                              
like image 247
JIbber4568 Avatar asked Apr 12 '13 15:04

JIbber4568


3 Answers

You can also use CallBack function to get Synchronous Behaviour -

var result = $('#main-container').load( 'html/Welcomeform.html', 
                function () {
                     if($("textarea").find("#mail-id")){
                        $("textarea#mail-id").val(email_id);
                     }
                     } );   
like image 65
Aparajita Avatar answered Sep 30 '22 21:09

Aparajita


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.

like image 39
plalx Avatar answered Sep 30 '22 19:09

plalx


var img = jQuery('<img src="' + url + '"/>').load(runner);  
function runner() {
    //run code here once image is loaded
}
like image 30
zarazan Avatar answered Sep 30 '22 21:09

zarazan