gospodin
gospodin

Reputation: 1201

jquery large data insertion into DOM

In js I am calling server via ajax and server is returning me processed data that I should insert into the dom.

$.fn.loadChildren = function() {
  var $li = $(this);

  ajaxQueue.add({
    url:     "myUrl.to",
    data:    "mydata",
    success: function(data) {

      $li.find("ul").html(data);
      ....

Issue is that data could be quite huge string and in that case in FF I am getting error msg "A script on this page may be busy, or it may have stopped responding..."

I tried using replaceWith instead of html but I still have the same problem.

I know there is a limitation for DOM insertion in every browser but I want to know is there anything else in jQuery optimization that I could try.

Thanks

Upvotes: 0

Views: 419

Answers (2)

Gabe
Gabe

Reputation: 50493

Narrow down the selector possibly?

$("#myul").html(data);

Try chunking the data. Something like this should help improve performance a bit.

var chunks = [];
var counter = 0;

chunks = breakApartDataIntoChunks(data);

setTimeout(function() { processChunk(chunks, counter); }, 0);

function processChunk(chunks, counter) {
    if (counter < chunks.length) {
        // insert this chunk into dom here
        $li.find("ul").append(chunks[counter]);
        counter++;
        setTimeout(function() { processChunk(chunks, counter); }, 1);
    }
}

Upvotes: 3

Nickydonna
Nickydonna

Reputation: 802

I'm guessing that what you return is not a huge piece of Html, but many elements, like a list or a table, what you could do is instead of returning html, return a JSON array, with those elements, and insert them one by one, something like this:

//response = ['<div>One Element</div>', '</div>Another Elmenet</div>']
for(var i = 0; i < response.lenght; i++) {
     $('ul#myElement').append($('<li>').html(response[i]));
}

Hope it helps

Upvotes: 1

Related Questions