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.
