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) { DOMParser.prototype.parseFromString = function(string, contenType) {
var div = document.createElement('div'); // Create a new document, since we're supposed to always return one.
div.innerHTML = string; var doc = document.implementation.createHTMLDocument(''),
return div.firstChild; 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; window.XMLSerializer = XMLSerializer;

View file

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