溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

web前端優(yōu)化時為何不建議使用css @import

發(fā)布時間:2021-10-08 11:33:54 來源:億速云 閱讀:174 作者:柒染 欄目:web開發(fā)

今天就跟大家聊聊有關web前端優(yōu)化時為何不建議使用css @import,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據(jù)這篇文章可以有所收獲。

曾經(jīng)研究web前端優(yōu)化時在網(wǎng)上多處看到這樣一條建議,大意是:

不要使用 css @import, 因為用這種方式加載css相當于把css放在了html底部。

關于這一點,我一直很疑惑: 為什么用@import就等于把css放在了頁面底部? 原理是什么?? 但一直不得而知,因為網(wǎng)絡文章一大抄,轉載的很多,去細究原因的卻很少。

直到今天,在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標簽的方式引入。

看完上述內容,你們對web前端優(yōu)化時為何不建議使用css @import有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI