Proposal: insertAdjacentTemplate function

#1

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,

0 Likes

#2

Could you provide a code example of how this can be done using existing APIs, for the sake of comparison?

0 Likes

#3

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.

0 Likes

#4

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);
    });
}
0 Likes

#5

Wait a second, can’t you just pass the clone to appendChild?

target.appendChild(
    document.importNode(template.content, true)
);

Demo: https://jsbin.com/voxitur/edit?html,js,output

0 Likes

#6

Good thought, but that would make the template go inside the target element. I want the template to be made adjacent to the target.

0 Likes

#7

To be clear… The main reason you are interested in this is mainly that there might be a kind of ‘transactional’ performance boost?

0 Likes

#8

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.

0 Likes

#9

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.?

0 Likes

#10

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).

0 Likes