前端效能優化之資源預載入與預載入
阿新 • • 發佈:2020-12-04
html5中的link 標籤 包含了幾個屬性,其中prefetch(空閒時載入)和preload(優先載入)可以讓我們在載入資源時提高使用者體驗。
這裡我用css樣式進行舉例,index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet"href="./css/index.css"> <link rel="prefetch" as="style" href="./css/other.css"> <title>Document</title> </head> <body> </body> </html>
在載入index.html的樣式時,我在引入index.css後加了下邊一句程式碼
<link rel="prefetch" as="style" href="./css/other.css"> 其意思為在空閒時載入other.css這一個檔案,此時瀏覽器中資源載入順序如下: 在載入了index.css後去載入了other.css 且other.css的優先順序為最低Lowest。 other.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./css/other.css"> <link rel="preload" as="style" href="./css/index.css"> <title>Document</title> </head> <body> </body> </html>
在載入other.html樣式時,我在引入other.css後加了下邊一句程式碼
<link rel="preload" as="style" href="./css/index.css"> 其意思為優先載入index.css這一個檔案,此時瀏覽器中資源載入順序如下: 可以看到瀏覽器優先載入了index.css這一檔案且other.css檔案其並未顯示Size,原因在於已經在index.html中載入並快取了other.css這個一樣式,其詳細資訊: 總結:我們可以通過在首頁新增prefetch讓瀏覽器在空閒時預載入其他頁面的資源,這樣在開啟其他頁面時就節省了載入時間,而使用preload能夠讓我們優先載入一些重要的資源,讓使用者能夠優先看到重要的內容,提高使用者體驗。 注:在使用時要新增as這一屬性宣告資源型別其值如下audio
: Audio file.document
: An HTML document intended to be embedded inside a<frame>
or<iframe>
.embed
: A resource to be embedded inside an<embed>
element.fetch
: Resource to be accessed by a fetch or XHR request, such as an ArrayBuffer or JSON file.font
: Font file.image
: Image file.object
: A resource to be embedded inside an<embed>
element.script
: JavaScript file.style
: Stylesheet.track
: WebVTT file.worker
: A JavaScript web worker or shared worker.video
: Video file.