What is the IFRAME advantage over shadowDOM?
Closed this issue · 6 comments
With a <load-file>
Web Component you have the choice of loading any content into DOM, or in shadowDOM to keep <style>
scoped... and even move (global) style (or any Node for that matter) to shadowDOM
No need to define it before being used like your htmz function; any existing <load-file>
will upgrade automagically.
/*
defining the <load-file> Web Component,
yes! the documenation is longer than the code
License: https://unlicense.org/
*/
customElements.define("load-file", class extends HTMLElement {
// declare default connectedCallback as async so await can be used
async connectedCallback(
// call connectedCallback with parameter to *replace* SVG (if <load-file> is not replaceWith)
src = this.getAttribute("src"),
// attach a shadowRoot if none exists (prevents displaying error when moving Nodes)
// declare as parameter to save 4 Bytes: 'let '
shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
) {
// load SVG file from src="" async, parse to text, add to shadowRoot.innerHTML
shadowRoot.innerHTML = await (await fetch(src)).text()
// append optional <tag [shadowRoot]> Elements from <load-file> innerHTML/lightDOM after parsed content
shadowRoot.append(...this.querySelectorAll("[shadowRoot]"))
// if "replaceWith" attribute exists
// then replace <load-file> with loaded content <load-file>
// childNodes instead of children to include #textNodes also
this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes)
}
})
source: a DEV.to Post from 2021
A lot more code, but looks interesting!
Could you share how I could have an a
element load content into another element using this code? The same way that htmz does.
Thank you.
You don't have to load it in another element, <load-file>
is the element
That means one can't use it to do what htmz does, so it's not an alternative.
Or replace shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
with shadowRoot = document.getElementById( this.getAttribute("for") )
And do <load-file src="..." for="myId">
its only modern JavaScript...
Hi @Danny-Engelman ! That isn't enough to replace htmz I'm afraid. You'd need some additional system for handling form submissions, links, and buttons to load new content into some other element.
Hi, htmz works on click.
<load-file>
solves a slightly different problem which is more like client-side includes / HTML imports (HTML proposal: whatwg/html#2791).
As others have mentioned, the advantage of iframes is that they can be target
ed with regular HTML, so it works with native elements like forms, links, and buttons.
Converting to Discussion.