Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is .html(stuff) synchronous or asynchronous?

Tags:

jquery

Suppose that stuff contains a considerable amount of html including an element that I want to fill in the line following this one:

$("#content").html(stuff);

Can the following line go ahead and fill the element defined in stuff or is it possible that the code is still running?

If the code will have finished running is it still possible that the element won't exist because the browser won't have rendered it yet?

I know that when I'm using .load (for the initial download of the element) that I'll have to use a callback, but the callback which comes with .html() isn't a do-this-when-done thing like they usually are, which is what has left me really confused. Given the similarity between .html and .load and knowing that .load is asynchronous my gut is telling me that .html must be too, but I can't find any indication either way. Please help.

like image 496
SteveC Avatar asked Jul 30 '14 10:07

SteveC


1 Answers

The answer is already given in the comments, but to explain it a bit:

The html method doesn't call a callback, it's just a function that returns the jQuery object when a parameter is given (or the html content otherwise).

Say for example when stuff is a very large string containing a lot of html and it would slow down your script, the rest of the script will wait until the html is in place.

So what you asked is certainly possible:

var stuff = '<div id="new">This is a placeholder text</div>';
$('#content').html(stuff);
$('#new').text('This is the real text');

But if stuff is loaded through ajax with .load(), the third line must be in the callback to replace the placeholder text as soon as the html is received from the server:

$('#content').load('content.php', function() {
    $('#new').text('This is the real text');
});

which is btw not more than a shortcut for this:

$.ajax({
    url: 'content.php',
    success: function(data) {
        $('#content').html(data);
        $('#new').text('This is the real text');
    }
});
like image 121
jazZRo Avatar answered Nov 09 '22 00:11

jazZRo