Appending HTML element with attributes

JavaScript performance comparison

Revision 8 of this test case created by Rafael

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<div id="screenshots">
</div>
      
<script>
Benchmark.prototype.setup = function() {
  var link = "something.html";
  var title = "Some Title";
  var el = "someImg.png";
  
  var isObject = function(o) {
    return typeof o === "object";
  };
  var isFunction = function(o) {
    return typeof o === "function";
  };
  var isString = function(o) {
    return typeof o === "string";
  };
  
  function mknode(tag, attrs, content) {
    var node = document.createElement(tag);
    var args = arguments,
      content;
    if (args.length > 1) {
      if (isObject(args[1])) {
        for (var i in args[1]) {
          if (!isFunction(args[1][i]))
            node.setAttribute(i, args[1][i])
        }
      } else
      if (isString(args[1]))
        content = args[1];
      if (isString(args[2]))
        content = args[2];
    }
    if (content)
      node.innerHTML = content;
  
    return node;
  }

};

Benchmark.prototype.teardown = function() {
  $("#screenshots").empty();

};
</script>

Preparation code output

<div id="screenshots"> </div>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
getElementById append
$(document.getElementById("screenshots")).append('<a href="' + link + '" title="' + title + '"><img src="' + el + '" alt="" width="200px" height="200px"></a>');
pending…
Create Element
var n = document.createElement("a");
n.setAttribute("href", link);
n.setAttribute("title", title);
n.innerHTML = '<img src="' + el + '" alt="" width="200px" height="200px">';
$(document.getElementById("screenshots")).append(n);
pending…
Original Code
$('#screenshots').append($('<a href="' + link + '" title="' + title + '"><img src="' + el + '" alt="" width="200px" height="200px"></a>'));
pending…
DOM scripting
$("#screenshots").append(
  $("<a>").attr({
    'href': link,
    'title': title
  }).append(
    $("<img>").attr({
      'src': el,
      'alt': '',
      'width': '200px',
      'height': '200px'
    })));
pending…
mknode()
$(document.getElementById("screenshots")).append(
  mknode('a', {
    'href': link,
    'title': title
  }, '<img src="' + el + '" alt="" width="200px" height="200px">'));
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments