Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Yeah, I have the similar need. I want to use <slot> mechanism, so I need shadow DOM, but I'd like to re-use styles, so that they don't need to be copied to each instance of the component. Aside from complicating things, it seems wasteful. It should be possible to use styles from the document's CSS to style the innards of a web component.

I'm still learning, and I'm still missing solution to this.

I know about var(--custom-prop), but that's limited, and still doesn't help with the waste of useless duplication of styles.



What I've done is kinda standardized the solution. I've made all my elements listen for a template tag in the html page that contains <link> tags to the stylesheets I use globally.

<template id="x-global-styles"> <link rel="stylesheet" href="some/sheet.css" /> </template> Kinda like that.

You can use prefetch in the main header to get all your styles in one shot, before page load, if you want.

Then I make my element, if the template is found, pump the innards of the template into itself so all my styles are available.

I use it in conjuction with tailwind so I can write atomic classes and include my atomic css with every element I desire.

From what I can tell, for the most part, my styles don't get reloaded every time. I could be wrong. They seem to get prefetched, if I use a prefetch, or loaded once, then cached. It seems that no matter how many elements I have on the page there are no external calls to get the stylesheet every time. One and done.

Correct me if I'm wrong here. It's just something I fiddled around with.


Very interesting! Thank you. I didn't realize you can use <link> inside web component. But it makes sense!

I read some more, and I reaized that it's probably meant to be that every component has its own small piece of CSS independent of the rest, so that you can use :host, and all the other trickery and so that least amount of CSS per component needs to be parsed and processed.

So I ended up writing a small pre-processor, that converts sass files into a js file with a variables containing styles for each component (like BUTTON_CSS, DIALOG_CSS, SPLIT_LAYOUT_CSS). I just hope that there's some optimization in the browser, such that when the same <style> content is used in multiple instances of the component, it is parsed/processed only once and the results cached for the other instances.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: