问题
I'm working on a lit-element project, and I got a problem that reset.css
cannot be applied to web components wrapped with shadow-root
I've tried this way, and I got this following error.
Refused to apply style from 'http://localhost:8080/style/static/reset.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
The code I tried is this:
<script>
var css = new CSSStyleSheet()
css.replace('@import url("./style/static/reset.css")')
document.adoptedStyleSheets = [css]
</script>
this is put into a html file.
How can I avoid this error, and apply the reset.css to the web components?
回答1:
Does it help to apply the replace import to the shadowroot as opposed to the document?
const node = document.createElement('div')
const shadow = node.attachShadow({ mode: 'open' })
shadow.adoptedStyleSheets = [sheet]
https://wicg.github.io/construct-stylesheets/#using-constructed-stylesheets
Edit -- addition for clarity:
The above addresses applying a style sheet possibly containing @import statements onto the frame to which your original question refers, the shadow-root node (element), however, because your code tries to apply the instantiated sheet to the document, to me, the question becomes a bit hazy.
The error you indicate seems indicative of code which attempts to apply a style sheet created in another document:
If you try to adopt a CSSStyleSheet that's constructed in a different Document, a "NotAllowedError" DOMException will be thrown.
https://github.com/WICG/construct-stylesheets/blob/gh-pages/explainer.md
来源:https://stackoverflow.com/questions/57325809/how-to-apply-global-css-to-web-components-through-shadow-dom