Can I make the browser visualize DOM changes before continuing with javascript?

I populate a table with a size of about 500 rows, which displays the browser for a few seconds to render while it looks frozen. This is why I want to show a message asking for user patience:

$.ajax({ url: '{{ search_url }}', success: function (response) { $('#progress').text('Rendering results, please wait...'); clear_table(); populate_table(response); } }); 

The message does not appear - obviously, the browser (tested in Chrome 23) buffers all DOM changes and displays them all at once.

As a workaround, I found that when I delay the completion of the table until the execution returns to the event loop, the message really displays:

 $.ajax({ url: '{{ search_url }}', success: function (response) { $('#progress').text('Rendering results, please wait...'); window.setTimeout(function () { clear_table(); populate_table(response); }, 0); } }); 

I wonder if this method will always work, or if there is a better way for this case.

+6
source share
1 answer

This is because Javascript execution is single-threaded. Thus, until all your JS code is executed, the browser will not do anything - in other words, it will freeze. To prevent this, I suggest you use the jQuery Async plugin (which is just a few lines of code) that will periodically transfer control to the browser (using setTimeout ). This will prevent the browser from freezing and display a wait message without any problems.

+3
source

All Articles