使用内联 CSS 而不是使用“块”是否存在性能问题?

发布于 2025-01-16 23:03:35 字数 724 浏览 2 评论 0原文

Vue 和 React 等现代框架从各个组件内的内联 CSS 开始。例如,在 Vue 单文件组件中,我们将所有 Javascript、HTML 和 CSS 包含在一个 .vue 文件中。通常有一个构建步骤或一些计算将这些更改编译成块,然后根据用户可见的组件将其加载到页面中。

我可以理解,这可能是为多个组件编译 CSS 并将其加载到页面中的最有效方法。

我的问题主要与性能有关。假设在渲染组件时,React 或 Vue 没有将所有组件样式编译成块,而是发送了以下内容:

<div id="someComponent">
    <!-- My component HTML goes here -->
</div>
<style>
     /* Associated styles */
     #someComponent {
         color: red;
     }
</style>

这意味着样式不是 CSS 块文件,而是简单地内联并包含在与它们相关的组件旁边实时网站。

我知道这很混乱,但我的问题是,这样做有任何性能问题吗?我认为这实际上可能会更高性能,因为加载了一个块需要一个 HTTP 请求,这显然会产生开销,而当用户打开网页时,这会包含在单个 HTTP 请求中。

Modern frameworks like Vue and React start with inline CSS inside individual components. For example, in a Vue single file component, we include all the Javascript, HTML, and CSS in one .vue file. There is usually a build step or some computation which compiles these changes into chunks, which are loaded into the page based on what components are visible to the user.

I can appreciate that this may be the most efficient way to compile CSS for multiple components and load it into a page.

My question relates primarily to performance. Suppose instead of compiling all of the component styles into chunks, React or Vue did sent this instead, when a component is rendered:

<div id="someComponent">
    <!-- My component HTML goes here -->
</div>
<style>
     /* Associated styles */
     #someComponent {
         color: red;
     }
</style>

That means instead of having a CSS chunk file, the styles are simply inlined and included beside the component they relate to on the live website.

I know this is messy, but my question is, are there any performance concerns with doing this? I would've thought this might actually be more performant, since loading a chunk requires an HTTP request, which obviously has an overhead, whereas this is included in a single HTTP request when the user opens the webpage.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缱倦旧时光 2025-01-23 23:03:35

对于任何想知道的人来说,虽然我无法进行非常广泛的测试,但采用这种方法似乎确实存在一些性能问题。由于 CSS 在不同时间加载,因此还会导致布局变化 (CLS)。

一般来说最好避免这样做,因为它似乎没有带来明显的好处。我最终采用的方法是通过正则表达式取出所有内联组件 CSS,并将其组合成一大块内联 CSS,从而切断 HTTP 请求。

For anyone wondering, although I wasn't able to do very extensive testing, there does seem to be some performance issues taking this approach. Also it leads to layout shifts (CLS) since the CSS is loaded at different times.

Good to avoid doing in general, as it seems to bring no discernible benefits. The approach I finally went with was to regex out all the inline component CSS and combine it into one large inline chunk of CSS, which cut out the HTTP request.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文