Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass in a set of predefined chunk keys to enable streaming preload for known components #1015

Open
Strydom opened this issue Dec 12, 2024 · 1 comment

Comments

@Strydom
Copy link

Strydom commented Dec 12, 2024

🚀 Feature Proposal

Enable streaming preloads for known components in a dynamic server rendering approach, by passing in a set of predefined chunk names to the ChunkExtractor.

Motivation

At my company we use a templating approach, where the template informs the app what components should be rendered.
Since we know ahead of render what is going to be included, we want to be able to provide that set of chunk names to ChunkExtractor, so that we can ask ChunkExtractor to generate the preload links for that set, server side with streaming enabled.

Example

import { ChunkExtractor } from '@loadable/server'

// This is the stats file generated by webpack loadable plugin
const statsFile = path.resolve('../dist/loadable-stats.json')

// We'd fetch the template server side before rendering the app and extract the component keys
const templateKeys = ['key1', 'key2', ...]

// We create an extractor from the statsFile and pass in the known component chunk names
const extractor = new ChunkExtractor({ statsFile, predefinedChunkNames: templateKeys })

// Get the preload links for the known components 
const linkTags = extractor.getPredefinedLinkTags()

const stream = SomeSteam

const head = `<html><head>${linkTags}</head><body>`

// Stream the head, ahead of the body so the preloads can start downloading
stream.send(head)

const body = chunkExtractor.collectChunks(<YourApp />)

// you'd then pipe the stream into the response object until it's done
// This takes a while with SSR data fetching etc, so the preloads will help things run in parallel a bit more
renderToNodeStream(body).pipe(stream, { end: false })

// and finalize the response with closing HTML
stream.on('end', () =>
  res.end(`${chunkExtractor.getScriptTags()}</body></html>`),
)

Pitch

Unlocks more complex rendering approaches to use preloading, that mix static/known and dynamic components.

@Strydom
Copy link
Author

Strydom commented Dec 13, 2024

I realised we might actually be able to do this without needing to change anything, we can getScriptElements before calling collectChunks and then filter that set by the keys?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant