Skip to content

Instantly share code, notes, and snippets.

@ghoullier
Created February 17, 2014 13:28
Show Gist options
  • Save ghoullier/9050473 to your computer and use it in GitHub Desktop.
Save ghoullier/9050473 to your computer and use it in GitHub Desktop.
DomBuilder comparison (Native vs String) : http://jsperf.com/test-dom-builder
;(function(root, doc) {
function AbstractDomBuilder(tagName, attrs, innerHTML) {
this.tagName = tagName || 'div'
this.attrs = attrs || {}
this.innerHTML = innerHTML || ''
}
AbstractDomBuilder.prototype.build = function() {}
function NativeDomBuilder() {
AbstractDomBuilder.apply(this, arguments)
}
NativeDomBuilder.prototype.build = function() {
var attrs = this.attrs
, node = document.createElement(this.tagName)
// Build properties
for (var attr in attrs) {
node.setAttribute(attr, attrs[attr])
}
// Inject innerHTML
node.innerHTML = this.innerHTML
return node
}
root.NativeDomBuilder = NativeDomBuilder
function StringDomBuilder() {
AbstractDomBuilder.apply(this, arguments)
// Use custom array to create properties
var properties = []
properties.toString = function() {
return this.join('')
}
this.properties = properties
// HTML parser
this.parser = document.createElement('div')
}
StringDomBuilder.prototype.build = function build() {
var attrs = this.attrs
, parser = this.parser
, properties = this.properties
, html = ['<', this.tagName, properties, '>', this.innerHTML, '</', this.tagName, '>']
// Clear parser
while (parser.firstChild) {
parser.removeChild(parse.firstChild)
}
// Clean properties
this.properties.length = 0
// Build properties
for (var attr in attrs) {
properties.push(' ', attr, '=', '"', attrs[attr], '"')
}
// Parse HTML String
parser.innerHTML = html.join('')
// Return parsed HTML
return parser.firstChild
}
root.StringDomBuilder = StringDomBuilder
}(this, this.document))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment