Skip to content

Instantly share code, notes, and snippets.

@developit
Last active August 29, 2015 14:22
Show Gist options
  • Save developit/a6611b33841a15c0e992 to your computer and use it in GitHub Desktop.
Save developit/a6611b33841a15c0e992 to your computer and use it in GitHub Desktop.
Custom Elements
(function() {
var elements = {};
function scan() {
[].forEach.call(
document.querySelectorAll('template[element]'),
function(el) {
var name = el.getAttribute('element'),
script = el.content.querySelector('script'),
js = script.innerHTML;
if (elements.hasOwnProperty(name)) return;
script.remove();
createCustomElement(name, js, [].map.call(
el.content.childNodes,
function(n) { return n.outerHTML; }
).join(''));
el.remove();
}
);
}
function createCustomElement(name, js, html) {
function F(){}
F.prototype = Object.create(HTMLElement.prototype);
var me = F.prototype;
extend(me, eval('('+js+')'));
var cb = me.createdCallback;
me.createdCallback = function() {
this.createShadowRoot();
this.shadowRoot.innerHTML = html;
if (typeof cb==='function') cb.call(this);
};
document.registerElement(name, F);
elements[name] = F;
}
function extend(base) {
for (var i=1, j; i<arguments.length; i++)
for (j in arguments[i])
if (arguments[i].hasOwnProperty(j))
base[j] = arguments[i][j];
return base;
}
scan();
window.addEventListener('load', scan);
setInterval(scan, 500);
window.attachCustomElements = scan;
}());
@developit
Copy link
Author

Sorry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment