Reputation: 10930
I have a page that requests most of it's content via Ajax. The returned html consists of 2 tables, which I render on the page. The code I am currently using:
$.post(myUrl, $('form').serialize(), function (data)
{
var $data = $(data);
$('#HeaderIndholdPanel').html($data.find('#GridView1'));
$('#SvarIndholdPanel').html($data.find('#Table1'));
}, 'html');
It does not get any easier, but does it get faster? The second table is almost 4 MB, so that explains, why it's slow - both tables must be rendered from one request, can't be split.
However I want to optimize it. I know that Jquery parses the html for scripts and other things. And when the table is replaced it cleans the events assigned to the elements.
Is there any way I can avoid that? It's not neseccary in my case. I know that my html doesn't have any scripts and I don't assign any avents to it. Should I return JSON instead and pass that to the native 'innerhtml' method? Or do you have any better ideas?
Upvotes: 0
Views: 81
Reputation: 36
I have found that $('#id').replaceWith(data)
works much better/faster than $('#id').html(data)
.
This is because $('#id').html(data)
takes the time to trace the object before replacing. When you command a simple replace it seems to ignore any existing value(s) and completes a straight swap.
I found this out when trying to swap out a select list that had thousands or options and using an ajax response to filter it. While watching the code I literally watched it deleted each select option one by one and then re-add it one by one.
Using .replaceWith(data)
, did a split/quick/1-for-1 replace.
$('#HeaderIndholdPanel').replaceWith($data.find('#GridView1'));
$('#SvarIndholdPanel').replaceWith($data.find('#Table1'));
Upvotes: 1