Is .html (stuff) synchronous or asynchronous?

Suppose that stuff contains a significant amount of html, including the element that I want to fill with the following line:

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

Is it possible to continue the next line and fill the element defined in stuff , or is it possible that the code is still working?

If the code is finished, is it still possible that the element will not exist because the browser has not yet displayed it?

I know that when I use .load (to bootstrap an element) that I will have to use a callback, but the callback that comes with .html () is not required when they are done, as usual, this is what I was really confused. Given the similarities between .html and .load and knowing that .load is asynchronous, my gut tells me that .html should also be, but I can’t find any signs anyway. Please, help.

+8
jquery
source share
1 answer

The answer is already indicated in the comments, but to explain this a bit:

The html method does not call a callback, it is just a function that returns a jQuery object when a parameter is specified (or the contents of the html otherwise).

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

What you requested 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 loaded via ajax using .load() , the third line should 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 nothing more than a shortcut for this:

 $.ajax({ url: 'content.php', success: function(data) { $('#content').html(data); $('#new').text('This is the real text'); } }); 
+1
source share

All Articles