Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force the browser to render out the DOM changes before continuing javascript execution?

I am populating a table with about 500 rows, which takes the browser a few seconds to render, while it appears frozen. This is why I want to display a message asking for the user's patience:

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

The message isn't displayed - apparently the browser (tested in Chrome 23) buffers all the DOM changes and renders them all in a single go.

As a workaround I found that when I delay populating the table until execution is back to the event loop the message is actually displayed:

$.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 technique for this case.

like image 944
AndreKR Avatar asked Nov 24 '12 00:11

AndreKR


People also ask

How do you refresh a DOM element?

The location reload() method in HTML DOM is used to reload the current document. This method refreshes the current documents. It is similar to the refresh button in the browser.

Are DOM updates synchronous?

log() yields this result isn't surprising because a DOM update is a synchronous event.

How the browser works when we update something in DOM?

The DOM and CSSOM tree structures are two independent structures. The DOM contains all the information about the page's HTML element's relationships, while the CSSOM contains information on how the elements are styled. OK, the browser now combines the DOM and CSSOM trees into something called a render tree.

How does the DOM get rendered?

When a web page is loaded, the browser first reads the HTML text and constructs DOM Tree from it. Then it processes the CSS whether that is inline, embedded, or external CSS and constructs the CSSOM Tree from it. After these trees are constructed, then it constructs the Render-Tree from it.


1 Answers

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

like image 89
Sidharth Mudgal Avatar answered Nov 14 '22 08:11

Sidharth Mudgal