noooooooob
noooooooob

Reputation: 1890

Why would jQuery detach improve efficiency?

For a ajax result handler:

$('.update-flight-status').on('click', function() {
  $.getJSON('/status', function(result) {
    var statusElements = $.map(result, function(status, index) {
      var listItem = $('<li></li>');
      $('<h3>'+status.name+'</h3>').appendTo(listItem);
      $('<p>'+status.status+'</p>').appendTo(listItem);
      return listItem;
    });
$('.status-list').html(statusElements); });

AND

$('.update-flight-status').on('click', function() {
  $.getJSON('/status', function(result) {
    var statusElements = $.map(result, function(status, index) {
      var listItem = $('<li></li>');
      $('<h3>'+status.name+'</h3>').appendTo(listItem);
      $('<p>'+status.status+'</p>').appendTo(listItem);
      return listItem;
    });
    $('.status-list').detach()
                  .html(statusElements)
                  .appendTo('.status');
  });
});

Why would the second example, where "detach" is used, is more efficient than the first one?

Upvotes: 0

Views: 74

Answers (2)

rupps
rupps

Reputation: 9907

jquery detach is the same as remove, only that it keeps jquery-specific assignments to that node, via data, or event handlers. This method comes in handy when you plan to re-attach the node to another point in the DOM.

In the first version you really can't tell if status-list is child of status, but in any case, you are NOT removing the node, so stuff like datas, event handlers, assigned classes, etc... DO remain.

In the second version, you remove status-list from the DOM, then modify it, then re-attach. I assume on the same place (but there's missing code, it's just a wild guess) I'd say it's in fact SLOWER than the first case, because the first case just modifies the HTML contents without bothering to detach/reattach anything.

The case where detach would improve efficiency is if you remove that node, and it has been heavily customized, with added classes, data, etc... then reattach it elsewhere, versus removing the node, recreating it, reassign all stuff, etc etc.

Upvotes: 1

Cyassin
Cyassin

Reputation: 1500

Detach is only useful and efficient when you specifically need to move an elements location, or prevent a 1000 items to be rendered when only one at a time can be seen.

Your example does not make detach look efficient, it looks as if the element has been positioned incorrectly from the start.

Upvotes: 0

Related Questions