Dynamically loading/unloading CSS based on route

I’d like to use a CSS framework (Semantic-UI) for one of my routes/components, but if I leave it permanently it messes with the layout of other routes/pages I’ve already built without it.

Is there an “elegant” way to load in or “activate” a CSS file on route change and then remove it again upon another route change?

2 Likes

Hi!

If you want to avoid leaking styles from within that component to the outside, afaik you basically have two options:

<require from="./styles.css" as="scoped"></require>

  1. Include styles inline with the component template and use shadow dom to encapsulate the component with @useShadowDOM():
<template>
   <style>
   </style>
   <content>
   </content>
</template>

Best

1 Like

Thanks, I’ll give that a shot.

1 Like

If anyone else finds this, I got it to work by including both the as="scoped" attribute on my css require and adding the @useShadowDOM decorator on my view model (so at least for me it wasn’t quite the either/or mentioned above). Works in both Firefox and Chrome.

Doing so allows me to import a CSS file (hand-written or from a library like Bootstrap, Materialize, or Fomantic) for just that component and not have it stick around to pollute further components when I route to them afterwards.

2 Likes

Did you inline the styles when trying to use @useShadowDOM only?

1 Like

I couldn’t because the CSS I wanted to have scoped were library files (Materialize and Fomantic). And my hand-written CSS is in Stylus, so I wouldn’t be able to inline it anyway (so far as I’m aware, using Webpack). But thanks for getting me 95% of the way there!

2 Likes

You’re welcome. Thank you for letting me know, that I was able to help. :smiley:

2 Likes