I'm experimenting with adding HTML to the DOM for a small game I'm writing. My design calls for a main-menu system to be brought up first, where-in I'd like to pop in and remove sets of elements.
My question is, what is the most efficient method to do this? After some research, I have implemented elements in the main body with IDs representing the menu section they contain. They look something like this:
<template id="main">
<div class="wrapper_inner">
<main id="main_screen">
<h1>Main menu</h1>
<nav class="vertical">
<button type="button">Characters</button>
<button type="button">Planets</button>
<button type="button">Export...</button>
<button type="button">Settings</button>
</nav>
</main>
</div>
</template>
Then, I call these functions to change menus:
function clearMenu()
{
var content = document.querySelector('.wrapper_inner');
if(content) document.body.removeChild(content);
}
function menuSystem(mode)
{
clearMenu();
document.body.appendChild(document.querySelector('template#'+mode).content.cloneNode(true));
}
UPDATE: The problem is within the
cloneNode()
function. It seemingly creates an inaccessible document-fragment in passing to the body. If someone can find a solution for this, I'll update best answer.
However... This is causing quite a problem in extended testing. I will only be changing menus a few times per session, I'm sure, but I'd like to maintain maximum efficiency. The problem shows up here:
function test()
{
console.log("start test...");
var start = new Date();
for(var i=0; i<10000; i++)
{
menuSystem("main");
}
clearMenu();
console.log("test completed in " + Math.round(((new Date())-start)/1000) + " secs");
}
This outputs around 5-7 seconds the first time, 16 seconds the second time. In Chrome Dev Tools, though I am struggling to understand the output, I can see for each unique "mode" I switch to it adds a documentfragment or two to memory, which is not removed...Also, in the Heap snapshot after running test(), HTMLBodyELement has two HTMLBodyElement objects in it, one with a normal number of elements, and another with thousands of them.
To reiterate: What is the best method to do what I require here? Can my current method be fixed? What's the deal, anyway?