Skip to content

Include scripts and styles only when component used #1465

Open

Description

@florian-lefebvre

Summary

Astro should support including an Astro component’s scripts and styles only when that component renders. This would help CMS page builders and other runtime component-selection patterns avoid shipping or running assets for components that a page does not use, while preserving Astro’s streaming behavior.

Background & Motivation

Astro builds component scripts and styles ahead of time. When a page imports a set of possible components and selects one at runtime, the page can include assets for candidates that never render. CMS page builders make this pattern common because editors choose page sections from a predefined component library.

Roadmap discussion #664 raised the mismatch between imported components and rendered components, especially for scripts. It also surfaced an important constraint: building assets at runtime is not a suitable direction, and buffering a full response to discover rendered components can affect streaming. Roadmap discussion #1054 focused on reducing unused assets in static CMS builds, while keeping existing streaming behavior for on-demand rendering.

Goals

  • Include scripts and styles associated with an Astro component only when that component renders.
  • Support pages that select components from CMS data or other runtime values.
  • Keep asset generation at build time. Do not require Vite or another bundler to run for each request.
  • Preserve response streaming where possible. Avoid requiring a page-wide opt-out from streaming.
  • Keep page-level and shared assets, preserve asset ordering, and avoid duplicate asset emission.

Non-goals

  • Support asset propagation for framework components.

Example

---
import Hero from '../components/Hero.astro?lazy';
import Cards from '../components/Cards.astro?lazy';

const components = { hero: Hero, cards: Cards };
const blocks = [{ type: 'hero', props: { title: 'Welcome' } }];
---

{blocks.map(({ type, props }) => {
  const Component = components[type];
  return <Component {...props} />;
})}

Activity

  1. moved this to Stage 2: Accepted Proposals, No RFC in Public Roadmapon Nov 9, 2026
  2. florian-lefebvre commented on Nov 12, 2026

    @florian-lefebvre
    MemberAuthor

    API ideas from my Spike PR:

    Global treeShakeComponents flag

    experimental.treeShakeComponents enables Astro to track which components render and remove assets owned only by components that do not render. The flag applies to the whole build. For on-demand pages, Astro must buffer the full response, which disables streaming.

    import { defineConfig } from 'astro/config';
    
    export default defineConfig({
      experimental: {
        treeShakeComponents: true,
      },
    });
    ---
    import Hero from '../components/Hero.astro';
    import Cards from '../components/Cards.astro';
    
    const components = { hero: Hero, cards: Cards };
    const Component = components[view.component];
    ---
    
    <Component {...view.props} />

    Pros

    • Keeps the authoring code for component maps unchanged.
    • Applies asset filtering across the site without wrapping each candidate component.

    Cons

    • Changes behavior globally rather than at a component boundary.
    • Buffers on-demand responses, which disables streaming and can increase time to first byte and memory use.
    • Requires build-time component chunk ownership and post-render asset pruning.

    astro:dynamic helper

    astro:dynamic takes a loader for each candidate component. The ?assets query exposes the component’s collected assets. dynamic() resolves the selected loader and uses head propagation to add those assets as the component renders, preserving streaming. The example spreads CMS data onto a generic Render component, so directive-shaped keys in that data need careful handling.

    ---
    import { dynamic } from 'astro:dynamic';
    
    const loaders = {
      hero: () => import('../components/Hero.astro?assets'),
      cards: () => import('../components/Cards.astro?assets'),
    };
    
    const Render = await dynamic(loaders[view.component]);
    ---
    
    <Render {...view.props} />

    Note: props could be moved to a componentProps property to avoid setting directives by mistake.

    Pros

    • Selects a component from a loader map and includes assets only for the selected component.
    • Uses head propagation to add assets during rendering, which preserves streaming.

    Cons

    • Requires an explicit loader map, dynamic imports, an experimental helper, and the ?assets query.
    • Requires an explicit prop boundary to keep CMS data from being interpreted as Astro directives (componentProps).

    Lazy component wrapper

    ?lazy could make each imported component a wrapper that loads or renders the underlying Astro component and adds its assets during rendering:

    ---
    import Hero from '../components/Hero.astro?lazy';
    import Cards from '../components/Cards.astro?lazy';
    
    const components = { hero: Hero, cards: Cards };
    const blocks = [{ type: 'hero', props: { title: 'Welcome' } }];
    ---
    
    {blocks.map(({ type, props }) => {
      const Component = components[type];
      return <Component {...props} />;
    })}

    Note: props could be moved to a componentProps property to avoid setting directives by mistake.

    Pros

    • Does not require a loader map
    • Could use head propagation to add assets during rendering and preserve streaming.

    Cons

    • Requires a new import-query transform and runtime wrapper.
    • Requires an explicit prop boundary to keep CMS data from being interpreted as Astro directives (componentProps).
  3. y-nk commented on Nov 13, 2026

    @y-nk

    imho the flag makes more sense but it's all about how to consider this addition:

    • it's a bug → flag makes sense (fixes automatically and globally)
    • it's a feature → dynamic makes more sense (gives control to the end user)
  4. florian-lefebvre commented on Nov 13, 2026

    @florian-lefebvre
    MemberAuthor

    I'm working on another spike which uses a global flag here withastro/astro#18730

  5. saimonsays199128 commented on Nov 19, 2026

    @saimonsays199128

    Data point from production, in case it helps choose between the options.

    I run 10 sites on Astro 7 with Wix-managed headless (built on @astrojs/cloudflare). They all use the pattern this targets: one catch-all route, page sections chosen from CMS data through a type → component map.

    1. Scripts are already fine. Since scripts render where their component renders, a page without the booking or form section ships none of their JS.
    2. Only component <style> would shrink. On a Tailwind-only site the same 33.5 KB of inlined CSS is on every page, because the utilities are one global stylesheet, so this change wouldn't touch it. On the sites with scoped <style> blocks (10 of 53 components on the largest), the savings would be real.
    3. Please keep streaming. These pages are edge-cached, and every cache miss is rendered on demand. Buffering the whole response (the global treeShakeComponents flag) would raise time to first byte on exactly those misses, which is where our field TTFB is worst. A per-component, streaming-preserving form (?lazy or astro:dynamic) would fit far better. We'd happily wrap the section map ourselves.
  6. y-nk commented on Nov 23, 2026

    @y-nk

    @saimonsays199128 how's "scripts are already fine"? could you elaborate? because it seems that what @florian-lefebvre is working on is exactly about making them fine, therefore if you already have a working solution maybe it's not a bug to solve?

  7. florian-lefebvre commented on Nov 25, 2026

    @florian-lefebvre
    MemberAuthor

    @ascorbic you hoped Stage 2 could be use to explore different designs. Do you have any ideas/opinions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    • Status
      Stage 2: Accepted Proposals, No RFC

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions