Since html imports are not yet well supported (Firefox, for instance, has no plans to do it), I've tried to mimic its use in importing custom elements via iframes.
The way I've tried to do that is by loading a script in the iframe that defines the custom element in the top browsing context; and the iframe could even be removed from the document after that. The reason I've tried to do so is because I'd like to dynamically define custom elements according to information I get at client side; and those custom elements use templates to be used in the shadow DOM.
I prefer to use templates instead of building the shadow DOM in the script in order to have clean code; that is why I'd like to mimic the import functionality with an iframe with all the templates instead of just loading a script where the shadow DOM is builded.
However, the way I've tried is not working (tested in google chrome and firefox):
// iframe.js
class XAElement extends HTMLElement{
constructor(){
super()
// Any customization here
}
// Any other methods for functionality
}
top.customElements.define('x-a', XAElement)
Is it allowed to define custom elements of the top browsing context in an iframe?
Note: The file iframe.html is any html file that loads this script; and the file index.html (in which the error happens) is any file that loads the iframe iframe.html.
Note 2: The error I get is afer super()
; however, if I comment the last line (in which I intend to define the custom element), no error happens.
If you want to mimic HTML Imports you'd better use the HTMLImports.min.js
library provided in the Github repository.
<script src="htmlimports.min.js"></script>
Note that HTML Imports native support in Chrome will be removed in the next release (version 73) as no consensus were found with Mozilla and Apple on this feature proposed by Google... but the above library will still work as a simple HTML loader.
Alternately you can load HTML content with fetch()
as described in this post about HTML Import alternatives.
If you still want to use an <iframe>
element to load a HTML file, you'll need to wait for the file to be laoded before accessing its content.
<iframe src="XA.html" onload="defineXA()"></iframe>
I don't think it's a good practise because it will create useless browsing context.