`Lighthouse 頁面性能 PWA 可訪問性(無障礙) 最佳實踐 SEO`。Lighthouse會對各個測試項的結果打分,並給出優化建議,這些打分標準和優化建議可以視為Google的網頁最佳實踐。 使用入門 運行Lighthouse的方式有三種:在開發者工具(Devtools)的Audits, ...
Lighthouse
是一個Google開源的自動化工具,主要用於改進網路應用(移動端)的質量。目前測試項包括頁面性能
、PWA
、可訪問性(無障礙)
、最佳實踐
、SEO
。Lighthouse會對各個測試項的結果打分,並給出優化建議,這些打分標準和優化建議可以視為Google的網頁最佳實踐。
使用入門
運行Lighthouse的方式有三種:在開發者工具(Devtools)的Audits,作為Chrome拓展程式使用,或者作為命令行工具使用。Chrome開發者工具不需要額外安裝,和擴展程式一樣提供了一個用戶友好的界面,方便讀取報告;擴展程式相對於開發者工具的優勢是更及時,不用等待Chrome發版就能體驗到最新的功能;命令行工具可以將Lighthouse集成到持續集成系統。
開發者工具
僅能在Chrome60及以上使用,因為之前版本的Chrome的開發者工具的audits面板還不是Lighthouse。
通過右上角的菜單或者快捷鍵(command+option+i)打開開發者工具,然後選擇audits面板,點擊Perform an audits會彈出一個options面板勾選測試項然後點擊Run audits即可。
Chrome拓展程式
在右上角或者菜單里點擊圖中圖標,Options可以配置測試項目,點擊Generate report即可測試。
命令行工具
安裝:
npm install -g lighthouse
# or use yarn:
# yarn global add lighthouse
使用:
lighthouse https://example.com
配置項:
$ lighthouse --help
lighthouse <url>
Logging:
--verbose Displays verbose logging [boolean]
--quiet Displays no progress, debug logs or errors [boolean]
Configuration:
--save-assets Save the trace contents & screenshots to disk [boolean]
--list-all-audits Prints a list of all available audits and exits [boolean]
--list-trace-categories Prints a list of all required trace categories and exits [boolean]
--additional-trace-categories Additional categories to capture with the trace (comma-delimited).
--config-path The path to the config JSON.
--chrome-flags Custom flags to pass to Chrome (space-delimited). For a full list of flags, see
http://peter.sh/experiments/chromium-command-line-switches/.
Environment variables:
CHROME_PATH: Explicit path of intended Chrome binary. If set must point to an executable of a build of
Chromium version 54.0 or later. By default, any detected Chrome Canary or Chrome (stable) will be launched.
[default: ""]
--perf Use a performance-test-only configuration [boolean]
--port The port to use for the debugging protocol. Use 0 for a random port [default: 0]
--hostname The hostname to use for the debugging protocol. [default: "localhost"]
--max-wait-for-load The timeout (in milliseconds) to wait before the page is considered done loading and the run should continue.
WARNING: Very high values can lead to large traces and instability [default: 45000]
--enable-error-reporting Enables error reporting, overriding any saved preference. --no-enable-error-reporting will do the opposite. More:
https://git.io/vFFTO
--gather-mode, -G Collect artifacts from a connected browser and save to disk. If audit-mode is not also enabled, the run will quit
early. [boolean]
--audit-mode, -A Process saved artifacts from disk [boolean]
Output:
--output Reporter for the results, supports multiple values [choices: "json", "html", "domhtml"] [default: "domhtml"]
--output-path The file path to output the results. Use 'stdout' to write to stdout.
If using JSON output, default is stdout.
If using HTML output, default is a file in the working directory with a name based on the test URL and date.
If using multiple outputs, --output-path is ignored.
Example: --output-path=./lighthouse-results.html
--view Open HTML report in your browser [boolean]
Options:
--help Show help [boolean]
--version Show version number [boolean]
--blocked-url-patterns Block any network requests to the specified URL patterns [array]
--disable-storage-reset Disable clearing the browser cache and other storage APIs before a run [boolean]
--disable-device-emulation Disable Nexus 5X emulation [boolean]
--disable-cpu-throttling Disable CPU throttling [boolean] [default: false]
--disable-network-throttling Disable network throttling [boolean]
--extra-headers Set extra HTTP Headers to pass with request [string]
Examples:
lighthouse <url> --view Opens the HTML report in a browser after the run completes
lighthouse <url> --config-path=./myconfig.js Runs Lighthouse with your own configuration: custom audits, report
generation, etc.
lighthouse <url> --output=json --output-path=./report.json --save-assets Save trace, screenshots, and named JSON report.
lighthouse <url> --disable-device-emulation --disable-network-throttling Disable device emulation
lighthouse <url> --chrome-flags="--window-size=412,732" Launch Chrome with a specific window size
lighthouse <url> --quiet --chrome-flags="--headless" Launch Headless Chrome, turn off logging
lighthouse <url> --extra-headers "{\"Cookie\":\"monster=blue\"}" Stringify\'d JSON HTTP Header key/value pairs to send in requests
lighthouse <url> --extra-headers=./path/to/file.json Path to JSON file of HTTP Header key/value pairs to send in requests
For more information on Lighthouse, see https://developers.google.com/web/tools/lighthouse/.
測試結果示例
最佳實踐
這些最佳實踐主要針對移動端或者Web應用。某些技術對瀏覽器版本要求較高,用之前最好在Can I use、MDN上查一下瀏覽器支持情況
打開外部鏈接使用rel="noopener"
當頁面使用 target="_blank" 跳轉至另一個頁面時,新頁面將與您的頁面在同一個進程上運行。 如果新頁面正在執行開銷極大的 JavaScript,您的頁面性能可能會受影響。最重要的是target="_blank”也是一個安全漏洞
。新頁面可以通過window.opener訪問舊頁面的window對象,並且它可以使用window.opener.location=newURL將舊頁面導航至不同的網址。所以當在新視窗或標簽中打開一個外部鏈接時,應該始終加上rel="noopener",例如:
<a href="https://examplepetstore.com" target="_blank" rel="noopener">...</a>
地址欄顏色應該和品牌顏色、網頁主題匹配
就是地址欄的背景顏色應該和品牌顏色一致
通過meta標簽實現的:
<meta name="theme-color" content="#ff6633">
不過僅在認可這個meta的瀏覽器上有效,比如Chrome for Android,實測pc、ios的Chrome、Safari無效。
如果場景能用上還是能提高一些用戶體驗的,避免了地址欄突兀。
避免使用AppCache
AppCache已被廢棄
考慮使用service worker的Cache API,另外現在ios 11.3也支持了service worker,未來一兩年應該有很大發展。
避免使用console.time()
如果使用console.time()測試頁面性能,請考慮使用User Timing API。其優勢包括:
- 高解析度時間戳
- 可導出的計時數據
與Chrome Devtools TImeline相集成。在 Timeline 錄製期間調用 User Timing 函數 performance.measure() 時,DevTools 自動將此測量結果添加到 Timeline 的結果中。
將console.time()替換為performance.mark()。如果需要測量兩個label之間經過的時間,則使用performance.measure()。User Timing API// 獲得命名時間戳 window.performance.mark('mark_fully_loaded'); // 獲得命名時間戳之間的時間間隔或者與PerformanceTiming的時間間隔 window.performance.measure('measure_load_from_dom', 'domComplete', 'mark_fully_loaded');
避免使用Date.now()
考慮改用performance.now()代替Date.now()。performance.now()可提供較高的時間戳解析度,並始終以恆定的速率增加,它不受系統時鐘(可以調整)的影響。performance.now()
// 獲取相對於navigationStart屬性中的時間戳為起點開始計時的精確到千分之一毫秒的時間戳
window.performance.now()
避免棄用的API
已棄用的API計劃從Chrome中移除,使用這些API後,被刪除後將導致網頁出錯。查看Chrome平臺狀態
避免使用document.write()
對於網速較慢(2G、3G或較慢的WLAN)的用戶,外部腳本通過document.write()動態註入會使頁面內容的顯示延遲數十秒。
避免巨大的網路負載
延遲請求直到需要它們
啟用文本壓縮
壓縮HTML、JS和CSS
使用Webp而不是JPEG或PNG
將JPEG圖像的壓縮級別設置為85
緩存請求
避免使用mutation events
以下mutation events會損害性能,在DOM事件規範中已經棄用:
- DOMAttrModified
- DOMAttributeNameChanged
- DOMCharacterDataModified
- DOMElementNameChanged
- DOMNodeInserted
- DOMNodeInsertedIntoDocument
- DOMNodeRemoved
- DOMNodeRemovedFromDocument
- DOMSubtreeModified
建議將每個mutation events替換成MutationObserver
避免使用舊版CSS Flexbox
2009年的舊Flexbox規範已棄用,其速度比最新的規範慢2.3倍。將頁面中的display:box及以box開頭的每個屬性替換成標準的Flexbox屬性。
避免在頁面載入時自動請求地理位置
頁面在載入時自動請求用戶位置會使用戶不信任頁面或感到困惑。應將此請求與用戶的手勢進行關聯,而不是在頁面載入時自動請求用戶的位置。
避免在頁面載入時自動請求通知許可權
好的通知需要做到及時、相關且準確。如果頁面在載入時要求許可權以發送通知,則這些通知可能與您的用戶無關或者不是他們的精準需求。為提高用戶體驗,最好是向用戶發送特定類型的通知,併在他們選擇加入後顯示許可權請求。
避免使用Web SQL
背景和前景應該有足夠的對比度
低對比度文本對於許多用戶來說很難或不可能讀取
使用Chrome擴展程式aXe可以分析出所有的可訪問性問題
按鈕有一個可訪問的名稱
沒有名字的按鈕對依賴屏幕閱讀器的用戶不可用。當一個按鈕沒有名字時,屏幕閱讀器會宣佈“按鈕”。
對
* aria-labelledby
Select seat:
9. 每個圖像都有一個alt屬性
信息性圖像應該具有alt包含該圖像內容的文本描述的屬性。屏幕閱讀器使視覺障礙的用戶能夠通過將文本內容轉換為可以使用的表格(如合成語音或盲文)來使用您的網站。屏幕閱讀器無法轉換圖像。因此,如果您的圖片包含重要信息,那麼視覺障礙用戶無法獲取該信息。
可以在DevTools的Console選項卡中使用以下命令來查找沒有alt屬性的圖片
$$('img:not([alt])');
在Console中$$()相當於document.querySelectorAll()
10. 配置HTML的Viewport meta標簽
如果沒有Viewport meta標簽,移動設備將以典型的桌面設備屏幕寬度渲染頁面,然後對頁面進行縮放以適合移動設備屏幕。通過Viewport meta標簽可以控制寬度和縮放比例。
[配置視口](https://developers.google.com/speed/docs/insights/ConfigureViewport?hl=zh-cn) [設置視口](https://developers.google.com/web/fundamentals/design-and-ux/responsive/?hl=zh-cn#set-the-viewport)
width=device-width鍵值對將視口寬度設置為設備寬度。在訪問頁面時,initial-scale=1鍵值對設置初始縮放級別。
... ...
11. 壓縮圖片(僅針對JPEG)
將每個圖像的壓縮級別設置為85或更低,像[TinyJPG](https://tinyjpg.com/)這樣的Web服務可以幫助自動化圖像優化的過程
##### 避免頁面存在不成功的HTTP狀態碼
搜索引擎可能無法正確索引返回不成功的HTTP狀態碼的頁面。
##### 允許用戶粘貼到密碼欄位中
密碼粘貼提高了安全性,因為它使用戶能夠使用密碼管理器。密碼管理員通常為用戶生成強密碼,安全地存儲密碼,然後在用戶需要登錄時自動將其粘貼到密碼欄位中。
刪除阻止用戶粘貼到密碼欄位的代碼。使用事件斷點中的Clipboard paste來打斷點,可以快速找到阻止粘貼密碼的代碼。比如下列這種阻止粘貼密碼的代碼:
let input = document.querySelector('input');
input.addEventListener('paste', (e) => {
e.preventDefault(); // This is what prevents pasting.
});
![dom-breakpoint.png](//upload-images.jianshu.io/upload_images/1726554-334b3f949eefa8c5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/800)
##### 避免DOM過大
大型的DOM樹會以多種方式降低頁面性能:
* 網路效率和負載性能,如果你的伺服器發送一個大的DOM樹,你可能會運送大量不必要的位元組。這也可能會減慢頁面載入時間,因為瀏覽器可能會解析許多沒有顯示在屏幕上的節點。
* 運行時性能。當用戶和腳本與頁面交互時,瀏覽器必須不斷重新計算節點的位置和樣式。一個大的DOM樹與複雜的樣式規則相結合可能會嚴重減慢渲染速度。
記憶體性能。如果使用通用查詢選擇器(例如,document.querySelectorAll('li') 您可能會無意中將引用存儲到大量的節點),這可能會壓倒用戶設備的記憶體功能。
一個最佳的DOM樹:
* 總共少於1500個節點。
* 最大深度為32個節點。
* 沒有超過60個子節點的父節點。
* 一般來說,只需要在需要時尋找創建DOM節點的方法,併在不再需要時將其銷毀。
如果你不能避免一個大型的DOM樹,改善渲染性能的另一種方法是簡化你的CSS選擇器。請參閱[減少風格計算的範圍和複雜性](https://developers.google.com/web/fundamentals/performance/rendering/reduce-the-scope-and-complexity-of-style-calculations)。
##### 使用被動事件監聽器以提升滾動性能
被動事件是新興的Web標準,可以顯著提高滾動性能,尤其在移動設備上。當使用touch事件監聽器(scroll事件不存在這個問題)進行滾動時,因為瀏覽器不知道你是否會取消滾動,它們總是等待監聽器執行完畢後才開始滾動,這樣就造成了明顯的延遲。事件監聽器options中使用passive:true表明監聽器永遠不會取消滾動,這樣瀏覽器就可以立即滾動。
在支持被動事件偵聽器的瀏覽器中,將偵聽器標記為passive即可:
document.addEventListener('touchstart', onTouchStart, {passive: true});
```
求贊,歡迎訪問我的博客