Node: Improve DOMParser#parseFromString() polyfill for Node.js

And no need to move imported SVG nodes into document, since we don't have styling in Node.js
This commit is contained in:
Jürg Lehni 2016-01-28 05:13:04 +01:00
parent 662b974104
commit e02e9f4643
2 changed files with 29 additions and 14 deletions

View file

@ -51,9 +51,18 @@ function DOMParser() {
}
DOMParser.prototype.parseFromString = function(string, contenType) {
var div = document.createElement('div');
div.innerHTML = string;
return div.firstChild;
// Create a new document, since we're supposed to always return one.
var doc = document.implementation.createHTMLDocument(''),
body = doc.body,
last;
// Set the body's HTML, then change the DOM according the specs.
body.innerHTML = string;
// Remove all top-level children (<html><head/><body/></html>)
while (last = doc.lastChild)
doc.removeChild(last);
// Insert the first child of the body at the top.
doc.appendChild(body.firstChild);
return doc;
};
window.XMLSerializer = XMLSerializer;

View file

@ -186,20 +186,26 @@ new function() {
// nodeNames still.
var importers = {
'#document': function (node, type, options, isRoot) {
var nodes = node.childNodes;
var nodes = node.childNodes,
move = !paper.agent.node;
for (var i = 0, l = nodes.length; i < l; i++) {
var child = nodes[i];
var child = nodes[i],
next;
if (child.nodeType === 1) {
// NOTE: We need to move the svg node into our current
// document, so default styles apply!
var next = child.nextSibling;
document.body.appendChild(child);
if (move) {
// NOTE: We need to move the svg node into our current
// document, so default styles apply!
next = child.nextSibling;
document.body.appendChild(child);
}
var item = importSVG(child, options, isRoot);
// After import, we move it back to where it was:
if (next) {
node.insertBefore(child, next);
} else {
node.appendChild(child);
if (move) {
// After import, we move it back to where it was:
if (next) {
node.insertBefore(child, next);
} else {
node.appendChild(child);
}
}
return item;
}