3 ms·
Bundling everything together and letting it be cached is how most single-page apps do it, yes. If the code isn't used by anything at all, it gets removed from
by chuckadams 3y ago
Bundling everything together and letting it be cached is how most single-page apps do it, yes. If the code isn't used by anything at all, it gets removed from the bundle entirely: that process is called "tree shaking". Modern frameworks like Nuxt also tend to do something called "code splitting": for example, I have a Nuxt app that contains, among others, pages like /vehicles, /drivers, and /fuel. Instead of creating a single giant js bundle, Nuxt creates several, including a file for code that's used by just the /vehicles page, a separate chunk for code that's only for the /drivers page, and so on, along with common chunks that are used by all of them. Script tags are then generated for each of these three pages so that when you hit one of the pages, you only get enough of the code for that page, and the rest is loaded when you navigate to another page. It's still a single-page app, but with multiple entry points, each one optimized to initially load only what that entry point needs, the rest being dynamically imported when needed. Each bundle's filename contains a hash of its content, so they can be cached forever (that does have consequences when upgrading though: a typical SPA has to do some some version checking and self-updating on its own, as the browser will otherwise be eager to serve stale code)
In dev though, one usually doesn't even bundle, and runs the app on a dev server that dynamically compiles and serves individual modules. When I initially load the app off the dev server, my browser makes close to a thousand requests for all those modules, but pipelining and caching make it all quite zippy regardless. Bundling is still faster and uses less bandwidth though, so for production one typically does still build a bundle (or several code-split ones).
There's gory details at https://webpack.js.org/guides/code-splitting/ https://webpack.js.org/guides/code-splitting/ (for webpack; other bundlers like Rollup work similarly) but frameworks like Next/Nuxt do it automatically as part of the build process.