印象中看過「css的link標籤不論放在哪(head or body)都會先載入」的這個說法,不過今天卻發現當Chrome在某些情況時,結果似乎會有點非預期。
首先我在head與body最後都各放一個link標籤,並且在onload時跳出alert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Document</title> | |
<script> | |
function cssLoaded () { | |
alert('css loaded!') | |
} | |
</script> | |
<link rel="stylesheet" href="style.css" onload="cssLoaded()"> | |
</head> | |
<body> | |
<div class="row"> | |
<div class="col">1</div> | |
<div class="col">2</div> | |
</div> | |
<link href="bootstrap.min.css" rel="stylesheet" onload="cssLoaded()"> | |
</body> | |
</html> |
在這個case,第一次alert時瀏覽器還是空白畫面,而第二次alert時,畫面上的row, col已被正確render了。看起來link不論放在哪都會先載的這個說法是成立的。
但奇怪的事情來了。當我把head裡的link拿掉時,chrome會呈現一個不穩定的結果。
- 有時第一個alert時已經出現了沒有樣式表喧染過的畫面,alert關閉後才被宣染。
- 有時則是跳一下尚未宣染的樣子,再出現已宣染過的樣子,然後再跳出alert。
- 有時卻是直經出現已經被宣染的樣子,然後再跳alert
但以上的這個情況,在firefox與safari都不會發生,alert的背後都是已被宣染的畫面。也就是說就只有chrome在head裡沒有css的link標籤時,有可能會出現非預期的render結果。
因此,當在css載入前有彈alert的話,可能就要注意一下。有可能會讓user看到還沒render好的畫面,也有可能只是看到畫面跳一下。
不過也不算什麼大問題。在想可能是因為要優化render速度或是什麼其他因素,導致在全部css載完前就先render畫面了。