Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding large amount of elements to DOM

Tags:

jquery

dom

in my web application, I have to retrive huge amount of data and to create a table with the data ( table with around 800 rows, 10 columns)
When, I am directly adding elements through append() method, the browser doesnot respond for a while.

for accessing the huge data, I am using web workers for ajax call.
As, we cannot manipulate DOM from web workers, what should I do??
thanks :)

edit:
If I want some functions like hide() (jQuery hide) over it, will innerHtml work??

like image 856
Navaneeth Avatar asked Sep 15 '12 15:09

Navaneeth


2 Answers

You can use some JavaScript templates engine to avoid manual appending the elements step by step or building the innerHTML string.

For example http://ejohn.org/blog/javascript-micro-templating.

Say you have a template somewhere in your HTML:

<script type="text/html" id="user_rows_tpl">
    <% for(var y = 0, l = users.length; l > y; y++) { %>
        <tr id="user-row-<%=y%>">
            <td><%=users[y].name%></td>
            <td><%=users[y].surname%></td>
            <td><%=users[y].age%></td>       
        </tr>
    <% } %>
</script>​

And then you're using this template in your JavaScript to render your objects:

<script type="text/javascript">
    var table = document.getElementById("userTable");
    table.innerHTML = tmpl("user_rows_tpl", {
        users: getUsers()
    });
</script>

For test I've created 1000 user objects and rendered them in table.
The average rendering time is about 20-25ms in Google Chrome. Not bad, isn't it?

DEMO

like image 111
Eugene Naydenov Avatar answered Sep 23 '22 14:09

Eugene Naydenov


You might want to use a table plugin that supports lazy insertion of DOM elements (i.e. on demand). DataTables offers a wealth of features, including this one. It will also help you cut down on the size of the code you have to write.

like image 35
Jon Avatar answered Sep 26 '22 14:09

Jon