--- /dev/null
+/**
+ * @vitest-environment jsdom
+ */
+
+import { template } from '../src'
+
+describe('api: template', () => {
+ test('create element', () => {
+ const t = template('<div>')
+ const div = t()
+ expect(div).toBeInstanceOf(HTMLDivElement)
+
+ const div2 = t()
+ expect(div2).toBeInstanceOf(HTMLDivElement)
+ expect(div2).not.toBe(div)
+ })
+})
--- /dev/null
+export const template = (str: string): (() => Node) => {
+ let cached = false
+ let node: Node
+ return () => {
+ if (!cached) {
+ cached = true
+ const t = document.createElement('template')
+ t.innerHTML = str
+ // first render: insert the node directly.
+ // this removes it from the template fragment to avoid keeping two copies
+ // of the inserted tree in memory, even if the template is used only once.
+ return (node = t.content.firstChild!)
+ } else {
+ // repeated renders: clone from cache. This is more performant and
+ // efficient when dealing with big lists where the template is repeated
+ // many times.
+ return node.cloneNode(true)
+ }
+ }
+}