slate icon indicating copy to clipboard operation
slate copied to clipboard

Is there a way to dynamically load css with slate?

Open adrianocr opened this issue 6 years ago • 2 comments

Not sure if this is a question that should be posed to the starter theme repo but here goes.

I'm looking for a way to load CSS that corresponds to a particular section only when necessary.

I split my scss files by section. For example if I have a homepage-carousel.liquid section, I also have a /src/styles/sections/homepage-carousel.scss file that corresponds to it. Right now to load the CSS for that I either have to include it globally in the theme.scss file, or via the index.js file. Both not ideal because homepage-carousel.liquid may actually never be used; it's an option that not required. In both cases I'd be loading unneeded CSS.

So I wanted to know if anyone (or if slate has a method) knows of a way to load CSS via the section file. As in, if the client / store owner decides to use homepage-carousel.liquid then pull in the SCSS/CSS file for it. Otherwise, don't.

adrianocr avatar Oct 02 '19 18:10 adrianocr

You could probably use a dynamic import in JS if I understand you correctly (apologies if I misunderstood).

If a condition is met (a particular section exists on the page) then use a dynamic import to grab that CSS.

Seems a little overkill IMO but up to you. In a current project I'm working on I'm loading JS/CSS on a per page basis, which is functionality that is built into slate, so that in itself might be enough to reduce your bundle sizes. https://shopify.github.io/slate/docs/template-and-layout-bundles

meandillar avatar Oct 03 '19 04:10 meandillar

You could write your styles directly into the section using a {% stylesheet 'scss' %} tag. This has a few drawbacks like not being connected to any variables you may be using in your main stylesheet, however you could utilize CSS Variables to get around that. This may feel a bit janky, but it's technically component based development. You're scoping your styles and logic to that section and making updates easier in the future. If you're using a Utility CSS approach this could also be a great method since you would only be adding light customizations to the section file, the majority of styling would be done with existing classes.

curiouscrusher avatar Oct 13 '19 18:10 curiouscrusher