Created
March 18, 2015 14:02
-
-
Save dchambers/0abcec9eaf529f993b9d to your computer and use it in GitHub Desktop.
importNode() polyfill for IE8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
if(!window.DocumentFragment && window.HTMLDocument) { | |
window.DocumentFragment = HTMLDocument; | |
} | |
if(!document.ELEMENT_NODE) { | |
document.ELEMENT_NODE = 1; | |
document.ATTRIBUTE_NODE = 2; | |
document.TEXT_NODE = 3; | |
document.CDATA_SECTION_NODE = 4; | |
document.ENTITY_REFERENCE_NODE = 5; | |
document.ENTITY_NODE = 6; | |
document.PROCESSING_INSTRUCTION_NODE = 7; | |
document.COMMENT_NODE = 8; | |
document.DOCUMENT_NODE = 9; | |
document.DOCUMENT_TYPE_NODE = 10; | |
document.DOCUMENT_FRAGMENT_NODE = 11; | |
document.NOTATION_NODE = 12; | |
} | |
if(!document.createElementNS) { | |
document.createElementNS = function(namespaceURI, qualifiedName) { | |
return document.createElement(qualifiedName); | |
}; | |
} | |
if(!document.importNode) { | |
document.importNode = function(node, deep) { | |
var a, i, il; | |
switch (node.nodeType) { | |
case document.ELEMENT_NODE: | |
var newNode = document.createElementNS(node.namespaceURI, node.nodeName); | |
if (node.attributes && node.attributes.length > 0) { | |
for (i = 0, il = node.attributes.length; i < il; i++) { | |
a = node.attributes[i]; | |
try { | |
newNode.setAttributeNS(a.namespaceURI, a.nodeName, node.getAttribute(a.nodeName)); | |
} | |
catch (err) { | |
// ignore this error... doesn't seem to make a difference | |
} | |
} | |
} | |
if (deep && node.childNodes && node.childNodes.length > 0) { | |
for (i = 0, il = node.childNodes.length; i < il; i++) { | |
newNode.appendChild(document.importNode(node.childNodes[i], deep)); | |
} | |
} | |
return newNode; | |
case document.TEXT_NODE: | |
case document.CDATA_SECTION_NODE: | |
return document.createTextNode(node.nodeValue); | |
case document.COMMENT_NODE: | |
return document.createComment(node.nodeValue); | |
case document.DOCUMENT_FRAGMENT_NODE: | |
docFragment = document.createDocumentFragment(); | |
for (i = 0, il = node.childNodes.length; i < il; ++i) { | |
docFragment.appendChild(document.importNode(node.childNodes[i], deep)); | |
} | |
return docFragment; | |
} | |
}; | |
} |
I think that in line 61 you should be
var docFragment = document.createDocumentFragment();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I needed an
importNode()
shim for IE8 I found a number of useful looking resources:but there were minor issues with all of them, and none of the solutions supported document fragments, which are needed to work with HTML5 templates. The polyfill above was adapted from these solutions, and seems to work for me.