樣式表放哪裡、怎麼引入,看似小事,卻會直接決定使用者看到的畫面是「先樸素後華麗」還是一次到位。
通常就是放進 head 元素內。CSS 屬於需要下載解析的資源,Firefox 與 IE 在等待樣式表傳輸完成之前不會渲染任何內容。唯有將 CSS 前置,瀏覽器在解析結構的過程中才能同步進行渲染。
This causes the blank white screen problem. The page is totally blank until the stylesheet at the bottom is downloaded, on the order of 6-10 seconds for this page. The browser is waiting for the stylesheet to be loaded before it renders anything else in the page, even the static text.
把樣式表放到頁面尾端,結果就是白屏等待,然後整頁風格突然跳換。這種落差對用戶體驗的傷害相當直接。
盡量採用下面的引入方式:
<link rel="stylesheet" href="https://www.example.com/style.css" type="text/css">
並減少 @import 的使用,更不要寫多層嵌套的 @import。原因很實際:在 IE 中,@import 的效果等同於把 <link> 放在頁面尾部。
This is a valid syntax, but, even though it's in the document's HEAD, it breaks progressive rendering and instead causes the blank white screen and Flash of Unstyled Content problems.
也就是說,即使語法完全合法、即使它確實寫在 head 裡,它依然會破壞漸進式渲染,造成白屏與樣式閃爍(Flash of Unstyled Content)。
兩個結論合起來其實很單純:樣式表要早一點被瀏覽器拿到,而且要用瀏覽器能並行處理的方式引入。