Reputation: 4923
I am creating some custom web components. One of the components is a light/dark theme switcher. However, this relies on a specific stylesheet being loaded.
I would like to output a warning if the correct stylesheet has not been loaded.
But, users have several different ways of loading stylesheets (e.g. link tag, @import statement, etc) and so it is not guaranteed that they will have loaded the correct sheet.
The stylesheet that is needed has some pretty specific custom variables and named styles in it. So I would like to know if there is any way from JavaScript (inside my web component), to check whether one of those variables or style names exists in the stylesheets loaded to the current page.
Upvotes: 1
Views: 2059
Reputation: 4923
Many thanks to RedRex for giving me the pointer. Custom variables are accessible but not from the document.style
. You have to use getComputedStyle
.
So, in my web component Class, I have a connectedCallback
function that runs whenever an instance of the component is added to the page.
connectedCallback() {
// Is the correct stylesheet loaded?
if ( !getComputedStyle(this).getPropertyValue('--uib-css').includes('uib-brand') )
console.warn('[uib-theme-changer] WARNING: It appears that you are not using uibuilder\'s uib-brand.css stylesheet. This component may not work as expected.')
} // ---- end of connectedCallback ---- //
In the CSS file, I have
:root, :root.light {
color-scheme: light dark;
/* Create a checkable var - helps web components know if this stylesheet is loaded.
* NOTE: no space between : and text! */
--uib-css:uib-brand;
}
Perhaps worth noting that web components are designed to limit the interaction between the light-DOM CSS and the shadowDom CSS. However, custom variables are designed to flow into your component.
Footnote: For the curious, I am writing some custom web components that will play nice with Node-RED and node-red-contrib-uibuilder.
Upvotes: 1