开发者

How to add new hidden HTML with best performance?

I have a large block of HTML that needs to be replaced, which includes fadeOut/fadeIn transitions. I can't figure out how to add the HTML to the page (hidden) without wrapping it in a div.

$.get('/ajax', function(n开发者_如何转开发ewHtml){
    var $newEvent = $('<div class="new-event" />').hide().html(newHtml);
    $('#content .event').fadeOut('slow', function(){
        $(this).remove(); //old event
        $newEvent.appendTo('#content').fadeIn('slow').removeClass('new-event'); //then remove the wrapper div that I didnt need in the first place
    });
});

What is the best way to do this while utilizing best practices for performance?

Solution:

For some reason, I thought that creating a new element like this: $(newHtml) was less efficient (bad performance) than html(newHtml). But apparently, they are the same as far as performance goes (I have no data to back this up other than my own observations).

So the following code is just as efficient as the previous:

$.get('/ajax', function(newHtml){
    var $newEvent = $(newHtml).hide();
    $('#content .event').fadeOut('slow', function(){
        $(this).remove(); //old event
        $newEvent.appendTo('#content').fadeIn('slow');
    });
});


When adding the code to the page, have top level elements all be hidden

<div style="display:none;">...</div>

When fadeIn is called jQuery automatically removes it for you.

If you can't modify the returned html just do it this way then,

$(newHtml).hide().appendTo('#content');

That will hide it before being added to the DOM.


How about something like

$('#content .event').fadeOut('slow', function()
{
    $(this).html(newHtml).fadeIn('slow');
});


Why you don't simply replace the content of .event instead of removing it and creating a new one?

$.get( '/ajax', function( newHtml )
{
    $( '#content .event' ).fadeOut( 'slow', function ()
    {
        $( this ).html( newHtml ).fadeIn( 'slow' );
    });
});

Edit

If you really need to remove the entire node, you can do this instead

$( this ).remove();
$( '<div class="new-event">' ).appendTo( $('#content') ).html( newHtml ).fadeIn( 'slow' );


You could just have it as a javascript string, and add it when you need.

var $newEvent = $(newHtml);
// and later on
$( '#content .event' ).fadeOut('slow', function ()
{
    $(this).append($newEvent).fadeIn( 'slow' );
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜