UNPKG

joicomponents

Version:

Design patterns to build native web components

73 lines (67 loc) 2.56 kB
<html> <head> <script> /** APP code**/ //my red-dot element class RedDot extends HTMLElement { connectedCallback() { this.style.background = "red"; this.style.borderRadius = "50%"; this.style.width = "150px"; this.style.height = "250px"; } } //app-specific loading method function loadMyElements() { customElements.define("red-dot", RedDot); } </script> <script> /** Polyfill code **/ //Setup: declare the function for loading script function loadScriptSync(url, onLoadFnAsString, onDOMContentLoaded) { const script = document.createElement("script"); script.src = url; script.setAttribute('onload', onLoadFnAsString); // script.setAttribute('onerror', "throw new URIError('The script " + url + " didn't load correctly.')"); document.write(script.outerHTML); document.addEventListener('DOMContentLoaded', onDOMContentLoaded); } //step 1: feature detection var CE = window.customElements; var SD = 'attachShadow' in Element.prototype && 'getRootNode' in Element.prototype; var ES6 = window.Promise && Array.from && window.URL && window.Symbol; var TE = (function () { // no real <template> because no `content` property (IE and older browsers) var t = document.createElement('template'); if (!('content' in t)) { return false; } // broken doc fragment (older Edge) if (!(t.content.cloneNode() instanceof DocumentFragment)) { return false; } // broken <template> cloning (Edge up to at least version 17) var t2 = document.createElement('template'); t2.content.appendChild(document.createElement('div')); t.content.appendChild(t2); var clone = t.cloneNode(true); return clone.content.childNodes.length !== 0 && clone.content.firstChild.content.childNodes.length !== 0 })(); //step 2: load polyfill async based on feature detection const base = "https://rawgit.com/webcomponents/webcomponentsjs/master/bundles/"; if (CE && SD && TE && ES6) { loadMyElements(); //[1] } else if (!CE && SD && TE && ES6) { loadScriptSync(base + "webcomponents-ce.js", "loadMyElements()"); //[2] } else if (!CE && !SD && TE && ES6) { console.log("yes"); loadScriptSync(base + "webcomponents-sd-ce.js", "loadMyElements()"); //[3] } else { /*if (!CE && !SD && !TE && !ES6) {*/ loadScriptSync(base + "webcomponents-sd-ce-te.js", "loadMyElements()"); //[4] } </script> </head> <body> <red-dot>\</red-dot> </body> </html>