Skip to content

Instantly share code, notes, and snippets.

@KonnorRogers
Created February 5, 2024 17:42
Show Gist options
  • Save KonnorRogers/d17b89eed5daad146e1ffcebef54714a to your computer and use it in GitHub Desktop.
Save KonnorRogers/d17b89eed5daad146e1ffcebef54714a to your computer and use it in GitHub Desktop.
A pseudo-morph algorithm for custom elements
const domParser = new DOMParser()
function morphCustomElement (currentEl) {
const tagName = currentEl.tagName.toLowerCase()
const isRegistered = Boolean(window.customElements.get(tagName))
if (!isRegistered) return
// TODO: This should ideally be a contextualFragment of where the element currently lives so it can have context of
// parent elements and the DOM. this is a placeholder.
const fakeDOM = domParser.parseFromString("<html><body></body></html>", "text/html")
const freshEl = document.createElement(tagName)
fakeDOM.body.append(freshEl)
// This will call the elements constructor() & connectedCallback()
// A lot of libraries use microtasks, so I wonder if this should really wait for a microtask
// and make the morphing function async.
// await new Promise((resolve) => resolve())
// Simple attribute writer. Clear the attributes from "currentEl" and then take attributes form "freshEl".
// This is what most morphing algorithms do today. They'll clear attributes they don't know about.
overwriteAttributes(freshEl, currentEl)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment