element.insertAdjacentTemplate(template: HTMLTemplateElement, position: InsertPosition)
This can be done programmatically, but I wonder if it could be done more quickly closer to the metal? I’m finding uses for this functionality,
element.insertAdjacentTemplate(template: HTMLTemplateElement, position: InsertPosition)
This can be done programmatically, but I wonder if it could be done more quickly closer to the metal? I’m finding uses for this functionality,
Could you provide a code example of how this can be done using existing APIs, for the sake of comparison?
Here’s some sample code (I’m sure it could be improved):
export function insertAdjacentTemplate(template, target, position) { const clone = document.importNode(template.content, true); let appendTarget = target; let isFirst = true; Array.from(clone.children).forEach(child => { const modifiedPosition = isFirst ? position : ‘afterend’; isFirst = false; appendTarget = appendTarget.insertAdjacentElement(modifiedPosition, child); }); }
So the amount of code might not be that much, but the act of having to essentially break the template into individual nodes to insert, makes me wonder if it’s possible if the browser could just slide the whole template in without having to di that, with better performance results.
Better formatting:
export function insertAdjacentTemplate(template, target, position) {
const clone = document.importNode(template.content, true);
let appendTarget = target;
let isFirst = true;
Array.from(clone.children).forEach(child => {
const modifiedPosition = isFirst ? position : 'afterend';
isFirst = false;
appendTarget = appendTarget.insertAdjacentElement(modifiedPosition, child);
});
}
Wait a second, can’t you just pass the clone to appendChild
?
target.appendChild(
document.importNode(template.content, true)
);
Good thought, but that would make the template go inside the target element. I want the template to be made adjacent to the target.
To be clear… The main reason you are interested in this is mainly that there might be a kind of ‘transactional’ performance boost?
Yes, I think if there’s a significant performance gain, then it kind of seems like there shouldn’t be much argument against adding it. A much weaker, second reason is if lots of people find such a function useful, that’s one less snippet of code that every application has to download. But I suspect that isn’t the case at this time.
Ah I see. insertAdjacentElement
does not accept a document fragment. This sounds like something that would be useful in general for document fragments. What about insertAdjacentElements
(notice the plural) that could accept sets of multiple elements, be it document fragment, node list, etc.?
InsertAdjacentElements could help, but the key issue is I want a function that can slide in a single chunk (document fragment) of HTML, hoping that fewer lower level operations can be made, resulting in a performance win (hopefully).