La única forma de comer un elefante: Code Splitting con Server Side Rendering

Rate this content
Bookmark

El code splitting es una forma de optimizar el rendimiento de nuestra aplicación al enviar menos código a los usuarios finales. La forma más común de code splitting es utilizar importaciones dinámicas después de una interacción del usuario. En nuestro caso, vamos a hablar sobre cómo cargar condicionalmente solo las partes de la aplicación que necesitamos durante el server side rendering. Vamos a discutir los problemas y las soluciones, para que puedas probarlo en tu propio proyecto.

9 min
17 Jun, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

La charla aborda los desafíos de manejar la manipulación del DOM con JavaScript y los problemas de rendimiento que surgen al usar SPAs. Explora la solución del server-side rendering (SSR) para abordar las preocupaciones de SEO, pero señala que el tamaño del paquete sigue siendo un problema. Se introduce el code splitting como una forma de cargar contenido dinámicamente, pero presenta desafíos para el SSR. El orador sugiere una solución utilizando vanilla.js que resuelve el problema sin problemas de escalabilidad.

Available in English

1. SSR Code Splitting and Vanilla.js

Short description:

Hola, mi nombre es Lena y hoy estoy aquí para hablarles sobre la única forma de comer un elefante. Todo comenzó en un momento en el que no existía React. Las páginas HTML se servían como cadenas de texto, pero JavaScript dificultaba la manipulación del DOM. Los héroes de JavaScript introdujeron las SPAs, pero el aumento de JavaScript resultó en un peor rendimiento. Para resolver el problema de SEO, se implementó el SSR, pero el tamaño del paquete seguía siendo un problema. Se introdujo la división de código para cargar contenido de forma dinámica, pero presentaba desafíos para el renderizado en el lado del servidor. La solución vanilla.js resuelve el problema sin problemas de escalabilidad.

Probablemente puedas recordarlo poco a poco, y tengo un aviso importante que hacer. No, recuerdo que es una conferencia de React, pero contaré mi breve historia sobre la división de código de SSR y por qué necesitas usarlos juntos principalmente con vanilla JS.

Todo comenzó en un momento en el que no existía React. Algunos recuerdan esos tiempos y otros ni siquiera pueden creer que hubo un tiempo en el que no existía React. Pero en ese momento, todas las páginas HTML se servían como cadenas de texto. No lo creerías. Pero todo el contenido era una cadena servida desde los servidores, y se veía algo así. Uno escribía todo el contenido HTML y había muchos, tantos como filas tenías, y en realidad todos estaban contentos en ese momento. Era bastante sencillo en realidad, hasta que, ya no lo era. Y probablemente puedas adivinar la razón. Era por culpa de JavaScript.

Se volvió demasiado tedioso manejar todo el JavaScript, toda la manipulación del DOM con jQuery, ya sabes, con herramientas de renderizado como EGS, handlebars y muchas más en todos los lenguajes de servidor, y también las solicitudes al servidor hicieron sufrir a las personas, y apenas puedo decirte quién sufrió más, si los usuarios o los desarrolladores, con todo su JavaScript, jQuery y handlebars. Entonces, llegaron los héroes de JavaScript y decidieron tener SPAs, aplicaciones de una sola página, y y se imaginaban renderizando todo el contenido en el lado del cliente y decidieron que el navegador podía manejar la navegación sin volver al servidor y pensaron, pensaron que era genial, y también decidieron que podían hacer enrutamiento en el lado del cliente, no porque fuera fácil, sino porque era difícil. Pero pudieron hacerlo. Y el HTML se volvió muy pequeño y superficial y ya no se renderizaba nada en el servidor. Todo se renderizaba en el lado del cliente con uno de los frameworks de JavaScript. Y ahí había más JavaScript, más herramientas para construirlo en un solo paquete y más problemas de JavaScript para resolver, más conferencias de JavaScript para hablar sobre estos problemas y nacieron nuevos monstruos. En realidad, más JavaScript resultó en paquetes más grandes, lo que resultó en un peor rendimiento, en la primera renderización, y en todo lo demás, y los usuarios comenzaron a sufrir y también los negocios comenzaron a sufrir porque el SEO era un problema. Los rastreadores no pueden leer JavaScript, necesitan cadenas de texto. Así que los héroes de JavaScript volvieron de nuevo y decidieron recuperar el SSR, pero esta vez conservaron el mismo JavaScript que habían escrito, porque era tan hermoso como para desecharlo y decidieron que la solución era renderizar este JavaScript que tenían como una cadena en el servidor y tener una función de JavaScript que devolviera una cadena. Así que esa fue una buena solución para el SSR y resolvió el problema de SEO. Pero no resolvió el problema del tamaño del paquete, ¿verdad? Así que estaban usando el mismo JavaScript tanto en el lado del cliente como en el lado del servidor. Entonces, los héroes de JavaScript decidieron que necesitaban idear una solución para la división de código. Y lo hicieron. Implementaron estas importaciones dinámicas. Aquí puedes ver que hay un problema con este código. No porque no esté en React, sino porque es asíncrono. Y sí resuelve el problema de un paquete grande de JavaScript. Puedes ver que ahora el contenido no está en un solo paquete, sino que se carga de forma dinámica. Pero las importaciones dinámicas son para el lado del cliente y no se pueden renderizar en el lado del servidor porque el servidor necesita hacerlo de forma sincrónica. Así que cuando tu contenido depende de la ruta, es decir, cuando necesitas este contenido de inmediato para que el cliente lo vea, puedes tener división de código tanto en el lado del servidor como en el lado del cliente. El único problema que necesitas resolver es decidir en qué entorno te encuentras y cargarlo de forma sincrónica cuando no estás en el entorno del lado del cliente y cargarlo de forma sincrónica cuando sí lo estás. Así que esta es la solución vanilla.js para este problema y aunque me gusta mucho vanilla.js, todos sabemos que no es escalable. Resuelve el problema, pero no es escalable. Pero afortunadamente tenemos React y una solución de biblioteca para ello, y tenemos componentes cargables y es tan fácil con los componentes cargables como lo escribí en vanilla.js Todo lo que necesitas hacer es proporcionarle a esta biblioteca información sobre todos los fragmentos que tienes y pedirle que renderice tu contenido como una cadena en el lado del servidor y luego Loadable decidirá como por arte de magia en qué entorno te encuentras y renderizará tu contenido tanto en el lado del servidor como en el lado del cliente y con división de código, por lo que no servirás paquetes grandes a tus clientes y vivieron felices para siempre SSR codes se casó con SSR y la división de código se casó con React y los componentes cargables y nuestros usuarios están felices y nuestros héroes de GS están listos para conquistar nuevos monstruos. Gracias

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
JSNation 2023JSNation 2023
26 min
When Optimizations Backfire
Top Content
Ever loaded a font from the Google Fonts CDN? Or added the loading=lazy attribute onto an image? These optimizations are recommended all over the web – but, sometimes, they make your app not faster but slower.
In this talk, Ivan will show when some common performance optimizations backfire – and what we need to do to avoid that.

Workshops on related topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
JSNation 2023JSNation 2023
174 min
Developing Dynamic Blogs with SvelteKit & Storyblok: A Hands-on Workshop
Featured WorkshopFree
This SvelteKit workshop explores the integration of 3rd party services, such as Storyblok, in a SvelteKit project. Participants will learn how to create a SvelteKit project, leverage Svelte components, and connect to external APIs. The workshop covers important concepts including SSR, CSR, static site generation, and deploying the application using adapters. By the end of the workshop, attendees will have a solid understanding of building SvelteKit applications with API integrations and be prepared for deployment.
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
React Advanced Conference 2023React Advanced Conference 2023
148 min
React Performance Debugging
Workshop
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Vue.js London 2023Vue.js London 2023
49 min
Maximize App Performance by Optimizing Web Fonts
WorkshopFree
You've just landed on a web page and you try to click a certain element, but just before you do, an ad loads on top of it and you end up clicking that thing instead.
That…that’s a layout shift. Everyone, developers and users alike, know that layout shifts are bad. And the later they happen, the more disruptive they are to users. In this workshop we're going to look into how web fonts cause layout shifts and explore a few strategies of loading web fonts without causing big layout shifts.
Table of Contents:What’s CLS and how it’s calculated?How fonts can cause CLS?Font loading strategies for minimizing CLSRecap and conclusion