使用Lighthouse进行网页性能测试



  • 简介

    Lighthouse可用于测试网页性能,以及给出具体的优化建议。lighthouse使用起来也特别方便,下面一起来了解下吧。

    安装

    使用lighthouse有两种方式:

    1. Chrome自带lighthouse功能
      替代文字
      打开开发者工具即可看到

    2. 命令行

    # 安装
    npm install lighthouse
    
    # 运行
    lighthouse https://google.com
    # 配置选项
    lighthouse https://google.com --only-categories=performance --output html --output-path ./report.html
    
    1. 实践
      这里直接使用Chrome开发者工具中的lighthouse对某网页进行了测试,以下是测试的总评分结果:
      替代文字
      评分分为几项:Performance、Accessibility、Best Paractices、SEO、Progressive Web App。关于这五个大的方面,每一项 lighthouse都会给出更具体的评分和优化建议。

    下面列举一下这次测试中对于Performance给出的具体建议:

    1. Does not use passive listeners to improve scrolling performance

    2. Serve static assets with an efficient cache policy

    3. Avoid an excessive DOM size

      A large DOM will increase memory usage, cause longer style calculations, and produce costly layout reflows. Learn more

    4. Defer offscreen images

    5. Minify CSS and JavaScript

    6. Preconnect to required origins

    Consider adding preconnect or dns-prefetch resource hints to establish early connections to important third-party origins

    1. Avoid multiple page redirects

    Redirects introduce additional delays before the page can be loaded

    1. Preload key requests

    Consider using <link rel=preload> to prioritize fetching resources that are currently requested later in page load

    1. Use video formats for animated content

    Large GIFs are inefficient for delivering animated content. Consider using MPEG4/WebM videos for animations and PNG/WebP for static images instead of GIF to save network bytes. Learn more

    1. Uses HTTP/2 for its own resources

    HTTP/2 offers many benefits over HTTP/1.1, including binary headers, multiplexing, and server push. Learn more.

    总结起来有两个方面:

    1. 网络方面

      • 延迟加载没有用到的CSS和Javascript资源,以及图片资源。

      • 文本(CSS、)压缩、使用更优化的图片格式,比如webp,以及替换大的GIF图。减小网络负载。

      • 静态文件使用合适的缓存策略。

      • Preconnect to required origins / Preload key requests

        preconnect or dns-prefetch / <link rel=preload>

      • 使用HTTP/2

        优点:二进制头,多路复用。

      • 避免大量的页面的重定向

    1. 代码方面

      • 监听滚动事件时尽量使用passive:true

        相当于告知浏览器此滚动监听事件不会阻止滚动

      • 避免大量的DOM渲染

        会增加内存占用,同时有很大的重排重绘开销

      • CSS减少嵌套

    通过这些建议我们就能对网站进行有针对性的改进了~
    另外,如果想了解lighthouse的实现原理,可以参考 Lighthouse 测试内幕


 

Copyright © 2018 bbs.dian.org.cn All rights reserved.

与 Dian 的连接断开,我们正在尝试重连,请耐心等待