JS DOMParser XML vs HTML

by Malin Jayakody

HTML

<button id="html">text/html test</button>
<button id="xml">application/xml test</button>
<div id="progress">Progress: 0 %</div>
<div id="form"></div>

JavaScript

// 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 < 6000; i++) {
  const inputSet = [];
  for (let j = 0; j < 14; 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();
...