开发者

(jquery): After Ajax: success, how to limit parsing in pieces and insert piece by piece into the DOM (trick to speed up)

开发者 https://www.devze.com 2022-12-25 00:59 出处:网络
Let\'s say on ajax success the function: xmlParser(xml) is called and the XML response contains about 1500 xml elements (for example: ...)

Let's say on ajax success the function: xmlParser(xml) is called and the XML response contains about 1500 xml elements (for example: ...)

Inside it looks like:

function xmlParser(xml){
    var xmlDOM = $(xml);  // dom object containing xml response

    xdom.find("book").each(function(){
        var $node = $(this);
        // parsing all the <book> nodes
    });
}

How can you say: pa开发者_如何学JAVArse only first 20 nodes from the xml response, do something with them. And you have a button,..when clicked parses the next 20 nodes...and so on.

So bassically, is there something like: children(20)....and a function wich will parse the next 20 nodes onClick.

thx


You can implement simple pagination on your xmlParser function. Try something like this:

function xmlParser(xml, page, perpage){
    // dom object containing xml response
    var xmlDOM = $(xml);

    // From what index to start showing
    var start = (page - 1) * perpage;

    // Find elements starting from start point using .gt() up to end point using .lt()
    xmlDOM.find("book").gt(start - 1).lt(perpage).each(function() {
        var $node = $(this);
        // Do your stuff
    });
}

// Usage
xmlParser(xml, 1, 20);

That would only handle the given amount of items on given page. Note that this example does not take into account minimum and maximum page counts etc, but should give you something to work on.

But as David V. noted in the comments, you really should just fetch the correct amount of results from the server in the first place rather than parse them in JS. Currently, you're downloading all of the 1500 records even if the user wants only the first 20.


This should do the work:

xdom.find("book:gt(lowerBound):lt(upperBound)").each(function(){
    var $node = $(this);
    // parsing all the <book> nodes
});

Where lowerBound and upperBound are your bounds.


I would store that data global on either a variable or jQuery'ish, with data.

function xmlParser(xml){
    $.data(document.body, 'xmlDOM', $(xml));  // dom object containing xml response      
});}

and then second function like

function getBooks(start, end){
  return($.data(document.body, 'xmlDOM').slice(start, end));
});

usage:

var books = getBooks(0,20);
 $.each(books, function(i){
   // do anything with objects, $('#something').append($(this));
 });
0

精彩评论

暂无评论...
验证码 换一张
取 消