jQuery .load(function) synchronous

29,656

Solution 1

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.

Solution 2

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);
                     }
                     } );   

Solution 3

var img = jQuery('<img src="' + url + '"/>').load(runner);  
function runner() {
    //run code here once image is loaded
}
Share:
29,656
JIbber4568
Author by

JIbber4568

Updated on June 26, 2020

Comments

  • JIbber4568
    JIbber4568 almost 4 years

    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.