【问题标题】:Why is creating elements from a text/html Document slower than creating them from an application/xml Document?为什么从 text/html 文档创建元素比从 application/xml 文档创建元素慢?
【发布时间】:2019-12-20 04:07:31
【问题描述】:

场景:我想创建一个表单并以 10 步为单位添加 20k+ 个输入字段。

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

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

问题

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

示例测试

以下 sn-p 是我要完成的基本示例。它对 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>

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

【问题讨论】:

    标签: javascript html xml dom domparser


    【解决方案1】:

    我应该继续使用“application/xml”mimetype 来创建大型 HTML DOM 层次结构吗?

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

    “text/html”这么慢有什么原因吗?”

    是的。首先,创建 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"

    在构建 HTML DOM 时使用“application/xml”有什么缺点吗?

    是的:您不是在构建 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。

    我希望你能从那里回答自己的第一个问题。

    【讨论】:

    • 这帮助我理解了为什么这两种方法的时间如此不同,即使输出形式看起来相同。我确实意识到的一件事是我无法提交使用“application/xml”文档创建的表单。我正在尝试看看是否可以混合使用这 2 个,以便在保持功能的同时提高性能。
    • 我使用答案中提供的新信息编辑了示例。通过使用 XMLSerializer 将 xml 设置为 innerHTML 作为字符串,我能够保留 application/xml 并创建有效的 HTML 表单。这样我可以更快地生成表单,但仍然能够像它是由 window.document.createElement (text/html Document) 创建的一样提交它。这是一种有效的方法吗?还是我仍在创建无效的 HTML?
    • @malinkody - 您仍在创建无效的 HTML。要进行同类测试,您必须做两件事。 1.将xml表单元素放入&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;元素中;和 2. (a) 使用 application/xhtml+xml 而不是 application/xml 作为您的 mime 类型,或者 (b) 使用 createElementNS("http://www.w3.org/1999/xhtml", "input") 而不是 createElement("input")
    猜你喜欢
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 2011-02-04
    • 1970-01-01
    • 2019-12-22
    • 2015-09-23
    • 1970-01-01
    相关资源
    最近更新 更多