javascript - 为什么从 text/html 文档创建元素比从 application/xml 文档创建元素慢?

标签 javascript html xml dom domparser

场景:我想创建一个表单并以每次 10 的步长附加 20k+ 个输入字段。

实现:我使用 JS DOMParser 创建一个 Document,并使用 Document.createElement 方法创建这些元素。

问题:使用 mimetype“text/html”通常比使用“application/xml”慢 5 倍以上。

问题:

  • 我应该继续使用“application/xml”mimetype 来创建大型 HTML DOM 层次结构吗?
  • “text/html”这么慢有什么原因吗?
  • 构建 HTML DOM 时使用“application/xml”有缺点吗?

示例测试

以下代码片段是我想要完成的任务的基本示例。它对 mimetype 选项进行了测试,并将耗时输出到控制台。

JSFiddle link

// Controls
const htmlTest = document.getElementById('html');
const xmlTest = document.getElementById('xml');
const progress = document.getElementById('progress');
const formContainer = document.getElementById('form');
// Generate input field data for test, 2000 sets of 10 inputs each.
const inputSets = [];
for (let i = 0; i < 2000; i++) {
  const inputSet = [];
  for (let j = 0; j < 10; j++) {
    inputSet.push({
      name: `abc[${i}]`,
      value: "123"
    });
  }
  inputSets.push(inputSet);
}
// Each set will be created in a task so that we can track progress
function runTask(task) {
  return new Promise(resolve => {
    setTimeout(() => {
      task();
      resolve();
    });
  });
}
// The actual create form function
function createForm(isXML, callback) {
  formContainer.innerHTML = '';
  const domparser = new DOMParser();
  let doc;
  if (isXML) {
    doc = domparser.parseFromString('<?xml version="1.0" encoding="UTF-8"?><form method="POST" action="targetAction" target="_blank"></form>', "application/xml");
  } else {
    doc = domparser.parseFromString('<form method="POST" action="targetAction" target="_blank"></form>', "text/html");
  }

  const form = doc.getElementsByTagName('form')[0];

  const start = Date.now();
  console.log('===================');
  console.log(`Started @: ${(new Date(start)).toISOString()}`);
  let i = 0;
  const processTasks = () => {
    runTask(() => {
      for (let input of inputSets[i]) {
        const inputNode = doc.createElement('input');
        inputNode.setAttribute('type', 'hidden');
        inputNode.setAttribute('name', input.name);
        inputNode.setAttribute('value', input.value);
        form.appendChild(inputNode);
      }
    }).then(() => {
      i++;
      if (i < inputSets.length) {
        progress.innerHTML = `Progress: ${Math.floor((i / inputSets.length) * 100)} %`;
        processTasks();
      } else {
        progress.innerHTML = 'Progress: 100 %'
        const serializer = new XMLSerializer();
        // EDIT: By using the xml serializer you can append valid HTML
        formContainer.innerHTML = serializer.serializeToString(form);
        const end = Date.now();
        console.log(`Ended @: ${(new Date(end)).toISOString()}`);
        console.log(`Time Elapsed: ${(end - start) / 1000} seconds`);
        console.log('===================');
        callback && callback();
      }
    });
  };
  // Append all the inputs
  processTasks();
}

htmlTest.onclick = () => {
  createForm(false, () => {
    const tForm = formContainer.getElementsByTagName('form')[0];
    tForm.submit();
  });

};

xmlTest.onclick = () => {
  createForm(true, () => {
    const tForm = formContainer.getElementsByTagName('form')[0];
    tForm.submit();
  });
};
<button id="html">text/html test</button>
<button id="xml">application/xml test</button>
<div id="progress">Progress: 0 %</div>
<div id="form"></div>

编辑:我使用答案中提供的新信息编辑了示例。我能够保留 application/xml 并通过使用 XMLSerializer 将 xml 设置为 innerHTML 作为字符串来创建有效的 HTML 表单。这样我可以更快地生成表单,但仍然能够提交它,就像它是由 window.document.createElement (text/html 文档)创建的一样。

最佳答案

Should I continue with the "application/xml" mimetype to create large HTML DOM hierarchies?

我不太明白你想要做什么(大局),所以很难说。

Is there a reason "text/html" is so slow?"

是的。首先,创建 HTML 文档比创建 XML 文档复杂得多。
只需检查您创建的两个 DOM,HTML 的元素就多得多。

const markup = '<form></form>'
console.log(
  'text/html',
  new XMLSerializer().serializeToString(
    new DOMParser().parseFromString(markup, 'text/html')
 )
);
console.log(
  'application/xml',
  new XMLSerializer().serializeToString(
    new DOMParser().parseFromString(markup, 'application/xml')
 )
);

现在,您的案例甚至不仅仅创建文档,而是在创建元素并为其设置属性之后创建文档。

您将在 HTML 中设置的属性是 IDL 属性,会触发很多副作用,而在 XML 版本中,它们不对应任何内容,因此设置速度更快。

const xmldoc = new DOMParser().parseFromString('<div/>', 'application/xml');
const xmlinput = xmldoc.createElement('input');
xmlinput.setAttribute('type', 'text');
console.log("xml input", xmlinput.type) // undefined

const htmldoc = new DOMParser().parseFromString('<div/>', 'text/html');
const htmlinput = htmldoc.createElement('input');
htmlinput.setAttribute('type', 'text');
console.log("html input", htmlinput.type) // "text"

Is there a downside to using "application/xml" when building an HTML DOM?

:您没有构建 HTML DOM。您创建的所有元素都不是从 HTMLElement 继承的,并且没有一个元素的行为与其 HTML 对应项相同。

const xmldoc = new DOMParser().parseFromString('<div/>', 'application/xml');
const xmlinput = xmldoc.createElement('input');
xmlinput.setAttribute('type', 'text');
console.log("is HTMLElement", xmlinput instanceof HTMLElement) // false

因此,如果您需要 HTML DOM,则无法将其解析为 XML DOM。

我希望您能够回答自己的第一个问题。

关于javascript - 为什么从 text/html 文档创建元素比从 application/xml 文档创建元素慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57480479/

相关文章:

xml - XML 中的元素和节点有什么区别?

javascript - Google 脚本中的全局变量(电子表格)

javascript - 使用 Angular JS 将常量注入(inject)其他模块配置

javascript - Angular 动态变量重命名

html - 如何在Notepad++中使用regex(正则表达式)删除所有不包含特定字符串的HTML和JSON代码?

xml - 使用 "and"的 XPath 表达式在 Microsoft Edge 中不起作用?

javascript - 当我们使用数组名称而不是扩展运算符时有什么区别?

java - 代号一错误 java.lang.NoSuchMethodError : javafx. scene.web.WebEngine.setUserDataDirectory(Ljava/io/File;)V

javascript - 使用 Bootstrap 网格系统在 AngularJS 中显示垂直堆叠的数据

.net - 在 office 07 中打开生成的 excel 文件时出现警告消息