While looking for improvements to injecting HTML fragments into a document (which I mentioned, in passing, when I looked at using Document Fragments) I decided to spend some more time with Internet Explorer’s insertAdjacentHTML method.
This method has been in Internet Explorer since version 4.0 – as well as is in the current release of Opera – and allows you to inject fragments of well-formed HTML into a variety of locations in a document.
The locations work as such (I list the equivalent terminology):
The method is only available on DOM elements (which makes sense) and is easy to use:
var ul = document.getElementById("list"); ul.insertAdjacentHTML("beforeEnd", "<li>A new li on the list.</li>"); ul.insertAdjacentHTML("beforeEnd", "<li>Another li!</li>");
At first glance the method appeared to work well and seemed to be relatively fast. Two questions remained, though: How fast is it in comparison to using the Document Fragment technique I outlined before and does it work for all the strange use-cases that exist?
- I created a test case to compare the three types of injection: The type we’ve been using in jQuery prior to the upcoming 1.3 release, the new Document Fragment technique we’ll be using in jQuery 1.3, and a case using insertAdjacentHTML (where applicable). While both the Document Fragment and insertAdjacentHTML cases were significantly faster than the old techniques used in jQuery the Document Fragment technique ended up being marginally faster in IE 6 (50ms vs. 80ms for insertAdjacentHTML).
- There’s a huge problem with insertAdjacentHTML: It doesn’t work on all HTML elements in IE 6 (specifically it doesn’t work on table, tbody, thead, or tr elements). Having gaps in the functionality is very undesirable (attempting to use insertAdjacentHTML on those elements causes an exception to pop up in IE 6).
- It doesn’t work on XML documents. Of course neither does innerHTML (at least not until browsers start to implement HTML 5 more completely). We’re stuck doing the traditional techniques used in libraries like jQuery.
So why spend all this time talking about a method that is relatively half-baked in the main browser that implements it? Because it’s going to be part of the HTML 5 specification. This means that we’re going to see a larger number of browsers start to implement this method (and hopefully it’ll encourage existing vendors to implement it more completely and efficiently).