web前端優化時為什么不建議使用css @import
2024-07-11 08:51:53
供稿:網友
曾經研究web前端優化時在網上多處看到這樣一條建議,大意是:
不要使用 css @import, 因為用這種方式加載css相當于把css放在了html底部。
關于這一點,我一直很疑惑: 為什么用@import就等于把css放在了頁面底部? 原理是什么?? 但一直不得而知,因為網絡文章一大抄,轉載的很多,去細究原因的卻很少。
直到今天,在google developers看一篇文章時,無意間找到了這個原因,原文如下:
Avoid CSS @import
Overview
Using CSS @import in an external stylesheet can add additional delays during the loading of a web page.
Details
CSS @importallows stylesheets to import other stylesheets. When CSS @import isused from an external stylesheet, the browser is unable to downloadthe stylesheets in parallel, which adds additional round-trip timesto the overall page load. For instance, iffirst.css contains the following content:
@import url("second.css")
The browser must download, parse, andexecute first.css before it is able to discover that itneeds to downloadsecond.css.
Recommendations
Use the <link> tag instead of CSS @import
Instead of @import, use a <link> tag for each stylesheet. This allows the browser to download stylesheets in parallel, which results in faster page load times:
<link rel="stylesheet" href="first.css">
<link rel="stylesheet" href="second.css">
我們確實要避免使用css @import, 但原因卻不是什么相當于放在了頁面底部,而是這樣做會導致css無法并行下載,因為使用@import引用的文件只有在引用它的那個css文件被下載、解析之后,瀏覽器才會知道還有另外一個css需要下載,這時才去下載,然后下載后開始解析、構建render tree等一系列操作。 星球瀏覽器在頁面所有css下載并解析完成后才會開始渲染頁面(Before a browser can begin to render a web page, it mustdownload and parse any stylesheets that are required to lay out thepage. Even if a stylesheet is in an external file that is cached,rendering is blocked until the browser loads the stylesheet from disk.),因此css @import引起的css解析延遲會加長頁面留白期。 所以,要盡量避免使用css @import而盡量采用link標簽的方式引入。