HTML partials/includes WebComponents-way - step 2
Custom element that stamps
by Tomek
HTML
<script src="https://cdn.jsdelivr.net/webcomponentsjs/0.7.22/webcomponents.min.js"></script><!-- Loads Web Components Polyfill -->
<body>
<template id="my-partial">
<h3>My partial...</h3>
</template>
<stamped-partial ref="my-partial"></stamped-partial>
Let's stamp it many times
<stamped-partial ref="my-partial"></stamped-partial>
</body>
<script>
(function(){
var StampedPartialPrototype = Object.create(HTMLElement.prototype);
StampedPartialPrototype.attachedCallback = function(){
this.stamp(this.getAttribute('ref'));
}
StampedPartialPrototype.attributeChangedCallback = function(name, oldVal, newVal){
if(name === 'ref'){
this.innerHTML = ''; // clear old content
//stamp partial
if(newVal){
this.stamp(id);
}
}
}
StampedPartialPrototype.stamp = function(id){
var partialTemplate = document.getElementById(id);
var partialInstance = document.importNode(partialTemplate.content, true);
this.appendChild(partialInstance);
}
document.registerElement('stamped-partial', {
prototype: StampedPartialPrototype
});
}())
</script>