pwa 开发工具_用于提高PWA性能CSS优化工具

pwa 开发工具

When styling websites or PWAs with CSS, you should analyze how CSS resources will affect performance. In this tutorial, we’ll use various tools and related techniques to help build a better PWA by focusing on CSS optimization. Specifically, we’ll remove the unused CSS, inline the critical path CSS, and minify the resulting code.

使用CSS对网站或PWA进行样式设置时,应分析CSS资源如何影响性能。 在本教程中,我们将通过关注CSS优化来使用各种工具和相关技术来帮助构建更好的PWA。 具体来说,我们将删除未使用CSS,内联关键路径CSS,并缩小结果代码。

The techniques can also be used to improve the performance of general websites and apps. We’ll be focusing on CSS optimization for PWAs since they should be fast and feel native on user devices.

该技术还可用于改善一般网站和应用程序的性能。 我们将专注于PWACSS优化,因为它们应该快速并在用户设备上感觉很自然。

Progressive web apps (PWAs) are web experiences that bring the best of both worlds: native mobile apps (installable from a store) and web apps (reachable from public URLs). Users can start using the application right away from their web browser without waiting for a download, installing, or needing extra space in the device.

渐进式Web应用程序(PWA)是一种结合了两全其美的Web体验:本机移动应用程序(可从商店安装)和Web应用程序(可从公共URL访问)。 用户可以立即从Web浏览器开始使用该应用程序,而无需等待下载,安装或需要设备中的额外空间。

Service workers and caching allow the app to work offline and when network connectivity is poor. Over time, the app could become faster as more assets are cached locally. PWAs can also be installed as an icon on the home screen and launched full-screen with an initial splash screen.

服务工作者和缓存使应用程序可以脱机工作,并且网络连接较差时也可以使用。 随着时间的流逝,随着更多资产在本地缓存,该应用可能会变得更快。 PWA也可以作为图标安装在主屏幕上,并以初始启动屏幕全屏启动。

审核的演示PWA (The Demo PWA to Audit)

Before learning how to audit a PWA for any CSS issues, you can get the code of a simple website with PWA features from this GitHub repository. The PWA uses an unminified version of Bootstrap v4 for CSS styling and displays a set of posts fetched from a statically generated JSON API. You can also use the hosted version of this demo, since learning how to build a PWA is beyond the scope of this tutorial.

在学习如何审核任何CSS问题的PWA之前,您可以从此GitHub存储库中获取具有PWA功能的简单网站的代码。 PWA使用Bootstrap v4的最小版本进行CSS样式设置,并显示从静态生成的JSON API提取的一组帖子。 您也可以使用此演示的托管版本,因为学习如何构建PWA超出了本教程的范围。

PWAs are simply web apps with additional features, including these elements:

PWA只是具有附加功能的Web应用程序,其中包括以下元素:

  • A manifest file. A JSON file provides the browser with information about the web application such as name, description, icons, the start URL, display factors etc.

    清单文件 。 JSON文件为浏览器提供有关Web应用程序的信息,例如名称,描述,图标,起始URL,显示因素等。

  • A service worker. A JavaScript file is used to cache the application shell (the minimum required HTML, CSS, and JavaScript for displaying the user interface) and proxying all network requests.

    服务工人 。 JavaScript文件用于缓存应用程序外壳程序(用于显示用户界面所需的最低HTML,CSS和JavaScript)并代理所有网络请求。

  • HTTPS. PWAs must be served from a secure origin.

    HTTPS 。 必须从安全来源提供PWA。

Here’s a screen shot of the application shell:

这是应用程序外壳的屏幕快照:

App shell

A screen shot of the application with data:

带有数据的应用程序的屏幕截图:

PWA

使用Google的Lighthouse进行审核 (Auditing with Google’s Lighthouse)

Lighthouse is an open-source auditing tool developed by Google. It can be used to improve the performance, accessibility and SEO of websites and progressive web apps.

Lighthouse是Google开发的一种开源审计工具。 它可以用来提高网站和渐进式Web应用程序的性能,可访问性和SEO。

Lighthouse can be accessed from the Audit tab in Chrome DevTools, programatically as a Node.js module and also as a CLI tool. It takes a URL and runs a series of audits to generate a report with optimization suggestions.

可以从Chrome DevTools的“ 审核”选项卡中以编程方式作为Node.js模块以及CLI工具来访问Lighthouse。 它使用一个URL并运行一系列审核以生成包含优化建议的报告。

You can apply different techniques either manually or using tools. This article describes how such tools can be used to remove redundant styles, extract the above-the-fold critical CSS, load the remaining CSS with JavaScript, and minify the resulting code.

您可以手动或使用工具来应用不同的技术。 本文介绍了如何使用这些工具来删除冗余样式,提取上述关键CSS,使用JavaScript加载其余CSS以及最小化所得到的代码。

Launch Chrome, visit the PWA address https://www.techiediaries.com/unoptimizedpwa/ and open Developer Tools (CTRL-Shift-I). From the Developer Tools, click the Audits panel:

启动Chrome,访问PWA地址https://www.techiediaries.com/unoptimizedpwa/并打开开发人员工具 ( CTRL-Shift-I )。 在开发人员工具中,单击“ 审核”面板:

Chrome Audit Panel

Next, click on Perform an audit…. A dialog will prompt you for the types of audit you want to perform. Keep all types selected and click the Run audit button.

接下来,单击“ 执行审核...” 。 对话框将提示您输入要执行的审核类型。 保持所有类型处于选中状态,然后单击“ 运行审核”按钮。

Chrome audits

Wait for Lighthouse to complete the auditing process and generate a report:

等待Lighthouse完成审核过程并生成报告:

Lighthouse report

The scores are calculated in a simulated environment. You’re unlikely to get the same results on your machine because they depend on hardware and network capabilities.

分数是在模拟环境中计算的。 您不太可能在计算机上获得相同的结果,因为它们取决于硬件和网络功能。

From the report, you can see a timeline which visually shows how the page is loaded. First meaningful paint, First Interactive and Consistently Interactive are key time points that describe how fast the page loaded. Our goal is to optimize these metrics according to the Critical Rendering Path.

从报告中,您可以看到一个时间轴,该时间轴直观地显示了页面的加载方式。 首次有意义的绘画首次互动持续互动是描述页面加载速度的关键时间点。 我们的目标是根据“ 关键渲染路径”优化这些指标。

关键渲染路径 (Critical Rendering Path)

The critical rendering path represents the steps the browser must take before it can render an initial page view (the visible area of the page or the “above-the-fold” area). When you visit a URL, the browser:

关键渲染路径表示浏览器可以渲染初始页面视图(页面的可见区域或“折叠上方”区域)之前必须采取的步骤。 当您访问URL时,浏览器:

  • starts to download the HTML which is parsed as it streams

    开始下载流式分析HTML
  • identifies and downloads external assets such as CSS, JavaScript, fonts and images

    识别并下载外部资源,例如CSS,JavaScript,字体和图像
  • parses and renders as necessary.

    分析并根据需要进行渲染。

Asset downloading and parsing can be done in parallel for assets such as images. However, CSS and JavaScript are render-blocking: the browser halts further processing until the file is downloaded and parsed. This is necessary because browsers are single-threaded and anything could occur. For example, the page redirects to another URL or changes layout styles.

资产的下载和解析可以并行进行,例如图像。 但是, CSS和JavaScript阻止了渲染:浏览器停止进一步处理,直到下载并解析文件为止。 这是必需的,因为浏览器是单线程的,任何事情都可能发生。 例如,页面重定向到另一个URL或更改布局样式。

Page performance should improve if the number of render-blocking assets is reduced.

如果减少渲染阻止资产的数量,则页面性能应该会提高。

利用Lighthouse机会优化CSS (CSS Optimization Using Lighthouse Opportunities)

Lighthouse provides guidelines to help optimize the application in the Opportunities section of the report. There are three suggestions to improve performance:

Lighthouse在报告的“ 机会”部分中提供了有助于优化应用程序的准则。 有三个建议可以提高性能:

  • reduce render-blocking CSS

    减少渲染阻止CSS
  • eliminate unused CSS rules

    消除未使用CSS规则
  • minify CSS.

    缩小CSS。
Lighthouse opportunities

CSS优化:删除未使用CSS规则 (CSS Optimization: Removing Unused CSS Rules)

Let’s start with the second Lighthouse opportunity, which relates to unused CSS rules. Expand the Unused CSS rules opportunity:

让我们从第二个Lighthouse机会开始,它与未使用CSS规则有关。 扩展未使用CSS规则机会:

Unused CSS Rules

Lighthouse estimates that 96% of the CSS in the bootstrap.css file is unused by the application. If we eliminate the unused CSS, network activity will reduce accordingly.

Lighthouse估计bootstrap.css文件中96%CSS未被应用程序使用。 如果我们消除了未使用CSS,网络活动将相应减少。

All the tools described here can be used as part of build system such as webpack, Gulp or Grunt, but this tutorial uses them on the command line.

此处描述的所有工具都可以用作构建系统的一部分,例如webpack,Gulp或Grunt,但是本教程在命令行上使用它们。

To eliminate the unused CSS styles, we’ll use PurifyCSS. Make sure you have Node.js installed on your machine, then install the tool globally using npm:

为了消除未使用CSS样式,我们将使用PurifyCSS 。 确保在计算机上安装了Node.js ,然后使用npm在全局安装该工具:

$ npm install -g purify-css

Next, make sure you’re inside your unoptimizedpwa folder and run the command:

接下来,确保您位于unoptimizedpwa文件夹中,然后运行以下命令:

$ purifycss styles/bootstrap.css index.html -o styles/purified.css -i
  • The first argument is the CSS file to purify.

    第一个参数是要净化CSS文件。

  • The second argument is the HTML file to check for used styles.

    第二个参数是HTML文件,用于检查使用的样式。
  • The -o option specifies the path and name of the result file to create.

    -o选项指定要创建的结果文件的路径和名称。

  • The -i option instructs the tool to display information about how much CSS was removed.

    -i选项指示该工具显示有关删除了多少CSS的信息。

(An -m option instructs the tool to minify the purified CSS, but we’ll use another tool for minification below.)

( -m选项指示该工具缩小纯化CSS,但下面我们将使用另一种缩小工具。)

In this case, we see PurifyCSS has reduced the file size by ~ 84.5%. This is not quite the 96% identified by Lighthouse, but the tools use different techniques.

在这种情况下,我们看到PurifyCSS has reduced the file size by ~ 84.5% 。 这并不是Lighthouse所确定的96%,但是这些工具使用了不同的技术。

Purified CSS

You can also use other tools to remove unused CSS such as uncss and you can read this article by Addy Osmani for more information.

您还可以使用其他工具删除未使用CSS(例如uncss),并且可以阅读Addy Osmani的这篇文章以获取更多信息。

You can now remove the original styles/bootstrap.css file and rename styles/purified.css to styles/bootstrap.css.

现在,您可以删除原始的styles/bootstrap.css文件,并将styles/purified.css重命名为styles/bootstrap.css

减少渲染阻止CSS (Reduce Render-Blocking CSS)

If we expand the Reduce render-blocking stylesheets opportunity, we can see more details:

如果我们扩展减少渲染阻止样式表的机会,我们可以看到更多详细信息:

Reduce render-blocking stylesheets

The bootstrap.css file delays the first paint of our application by 678ms. Not all styles are necessary for above-the-fold rendering, so we can do the following:

bootstrap.css文件将我们的应用程序的第一次绘制延迟了678ms。 并非所有样式都需要首屏渲染,因此我们可以执行以下操作:

  1. Extract the critical CSS from bootstrap.css and inline it in the index.html file using a <style> tag. This reduces the number of HTTP requests and is less code for the browser to parse.

    bootstrap.css提取关键CSS,并使用<style>标记将其内联到index.html文件中。 这减少了HTTP请求的数量,并减少了浏览器解析的代码。

  2. Deliver the remaining non-critical styles after the top of the page has rendered.

    在页面顶部呈现后,传递其余的非关键样式。

We’ll use Critical CSS Extractor, a Chrome extension to extract Critical CSS rules for the current page. Once you’ve installed this extension, you’ll see a new panel — Critical CSS — in DevTools.

我们将使用Critical CSS Extractor (Chrome扩展程序)为当前页面提取Critical CSS规则。 安装此扩展程序后,您将在DevTools中看到一个新面板-Critical CSS

Chrome does the hard work for us. Open DevTools again with the site still active and select the Critical CSS tab. Click the Extract Critical CSS button to download the critical CSS file:

Chrome为我们完成了艰苦的工作。 在站点仍处于活动状态的情况下,再次打开DevTools,然后选择“ 关键CSS”选项卡。 单击“ 提取关键CSS”按钮以下载关键CSS文件:

Chrome Extract Critical CSS tab

Open index.html and add the content of this critical CSS file within a <style> tag in the HTML <head>.

打开index.html并在HTML <head><style>标记内添加此关键CSS文件的内容。

未缩小CSS (Unminified CSS)

The CSS file is still required with all styles, but we can minify it to reduce its size.

所有样式仍然都需要CSS文件,但是我们可以将其缩小以减小其大小。

Expand the Minify CSS opportunity in the Lighthouse audit:

在Lighthouse审核中扩展Minify CSS机会:

Minify CSS

To minify the file, we can use tools such as:

要缩小文件,我们可以使用以下工具:

  • cssnano— a modular minifier, built on top of PostCSS

    cssnano —一个模块化的缩小器,建立在PostCSS之上

  • csso — a CSS minifier with structural optimizations.

    csso-具有结构优化功能CSS缩小器。

To use cssnano, from the unoptimizedpwa folder, run the following command to install cssnano locally:

要使用cssnano,unoptimizedpwa文件夹,运行以下命令来cssnano本地安装:

npm install cssnano

Next, install the PostCSS CLI globally using:

接下来,使用以下命令全局安装PostCSS CLI

npm install postcss-cli --global

Add a new file named postcss.config.js with the following (default) cssnano configuration parameters:

使用以下(默认)cssnano配置参数添加一个名为postcss.config.js的新文件:

module.exports = {
    plugins: [
        require('cssnano')({
            preset: 'default',
        }),
    ],
};

The cssnano guide provides more information about configuration presets.

cssnano指南提供了有关配置预设的更多信息。

Minify the bootstrap.css file by running:

通过运行以下命令来缩小bootstrap.css文件:

postcss styles/bootstrap.css > styles/bootstrap.min.css

使用JavaScript延迟Bootstrap加载 (Deferring Bootstrap Loading with JavaScript)

To prevent the CSS file from render-blocking, it can be loaded at the end of the page using JavaScript after the DOM is ready. Add the following JavaScript code snippet to index.html just before the closing </body> tag:

为了防止CSS文件呈现阻塞,可以在DOM准备就绪后使用JavaScript在页面末尾加载它。 在</body>标记之前,将以下JavaScript代码段添加到index.html

<script>
const link = document.createElement('link');
link.href = 'styles/bootstrap.min.css';
link.type = 'text/css';
link.rel = 'stylesheet';
const  link0 = document.getElementsByTagName('link')[0];
link0.parentNode.insertBefore(link, link0);
</script>

If you inspect your DOM after the page has loaded, you’ll find the inserted <link> tag inside the <head> tag:

如果在页面加载后检查DOM,则会在<head>标记内找到插入的<link> <head>标记:

Page head

检查优化 (Checking the Optimizations)

We can run Lighthouse again against the optimized PWA. The results:

我们可以再次针对优化的PWA运行Lighthouse。 结果:

Lighthouse report

The performance score has improved.

性能得分有所提高。

Lighthouse still reports further unused CSS rules could be removed. This could occur because PurifyCSS doesn’tt remove similar named selectors.

Lighthouse仍然报告可以删除进一步的未使用CSS规则。 这是因为PurifyCSS不会删除相似的命名选择器

The final optimized PWA is available from this GitHub repository.

最终优化的PWA可从该GitHub存储库中获得

类似工具 (Similar Tools)

There are many alternative tools to the ones we used in this tutorial. Here’s a list of well-known tools for purifying, minifying and extracting critical CSS:

除了本教程中使用的工具以外,还有许多其他工具。 以下是一些用于净化,缩小和提取关键CSS的知名工具的列表:

  • csso — a CSS minifier with structural optimizations

    csso-具有结构优化功能CSS缩小器

  • critical, a tool by Addy Osmani to extract and inline critical-path CSS in HTML pages

    criticalAddy Osmani的工具,用于在HTML页面中提取并内嵌关键路径CSS

  • uncss, a tool for removing unused CSS from your stylesheets that works across multiple files and supports Javascript-injected CSS

    uncss ,一种用于从样式表中删除未使用CSS的工具,该工具可跨多个文件工作并支持Javascript注入CSS

  • purgecss, a tool for removing unused CSS.

    purgecss ,用于删除未使用CSS的工具。

结论 (Conclusion)

In this tutorial, we moved towards CSS optimization by removing redundant code, inlining critical assets and minifying the resulting CSS. As a result, the PWA will download quicker and render faster. Similar tools and techniques can be used on your sites and apps for optimizing CSS to increase performance.

在本教程中,我们通过删除冗余代码,内联关键资产并最小化生成CSS来实现CSS优化。 结果,PWA将更快地下载并更快地渲染。 可以在您的网站和应用程序上使用类似的工具和技术来优化CSS以提高性能。

翻译自: https://www.sitepoint.com/css-optimization-boosting-pwa-performance/

pwa 开发工具

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值