Showing posts with label optimization. Show all posts
Showing posts with label optimization. Show all posts

Wednesday, April 25, 2012

optimizes often used templates

In the todomvc posts I've been doing the todo creates it's dom from a string:

todomvc.todocontrol.prototype.createDom = function() {
  this.el = goog.dom.htmlToDocumentFragment('<li>' +
          '<div class="view">' +
            '<input class="toggle" type="checkbox">' +
            '<label>' + this.getModel().get('text') + '</label>' +
            '<a class="destroy"></a>' +
          '</div>' +
          '<input class="edit" type="text" value="Create a TodoMVC template">' +
        '</li>');
 this.setElementInternal(this.el);
};

But we can do one better. The htmlToDocumentFragment works by setting the string as the innerHTML of a div then grabbing the dom underneath it. A better option would be to set the DOM structure once and then use a deep clone to get the structure for other todos. So how should it look?

todomvc.todocontrol.dom = goog.dom.htmlToDocumentFragment('<li>' +
        '<div class="view">' +
          '<input class="toggle" type="checkbox">' +
          '<label>' + this.getModel().get('text') + '</label>' +
          '<a class="destroy"></a>' +
        '</div>' +
        '<input class="edit" type="text" value="Create a TodoMVC template">' +
      '</li>');

todomvc.todocontrol.prototype.createDom = function() {
  this.el = todomvc.todocontrol.dom.cloneNode(true);
 this.setElementInternal(this.el);
};

What we do is the first time the file is opened we set a class variable on mvc.todocontrol and then we can just do a deep clone of that making things faster which could be very useful if we start to have thousands of todo items on the page.