Open
Description
Thinking about declarative custom elements and playing with a load-file
custom element that does load a file using the fetch API to create a shadow DOM root, I'm wondering if we absolutely need to have DOM parts, at least initially, for declarative custom elements.
My take on this is that you can have declarative custom elements without any form of templating:
- the main document includes a custom elements declared in an inline template or in an external file that is taken as template content
- when the custom elements is used, the template in put as it is as shadow root without any templating whatsoever
- slots can be used for minimal templating needs
- any inline script tag within the template is executed when the template is instanciated as a shadow root, this script can perform DOM transformations to adjust the markup on the context
- the script can use the
slotchange
event to detect if the content of a slot is changed to adjust the DOM
Example using an import link idea:
<head>
<link rel="custom-element" href="custom-element.html" />
</head>
<body>
<custom-element>
<span slot="data" data-title="Abc" data-code="123"></span>
</custom-element>
</body>
and in custom-element.html:
<template element="custom-element">
<div>
<slot name="data"></slot><!-- display none on this seems to block slot filling -->
<h1>This is custom element title <span class="title">unknown</span></h1>
<p>Code is <span class="code">000</span></p>
<script>
(() => {
let titleElem = document.currentScript.parentElement.querySelector('.title')
let codeElem = document.currentScript.parentElement.querySelector('.code')
let dataSlot = document.currentScript.parentElement.querySelector('slot[name=data]')
dataSlot.addEventListener('slotchange', (e) => bindData())
bindData()
function bindData(){
let dataset = dataSlot.assignedNodes()[0]?.dataset
titleElem.textContent = dataset?.title
codeElem.textContent = dataset?.code
}
})()
</script>
</div>
</template>
Here, vanilla javascript is used to perform templating, but any templating library can be used in the same way as long as the template respects standard HTML syntax.
DOM Parts can be used later to incrementally improve on this.
Metadata
Metadata
Assignees
Labels
No labels