您的位置:首页 > 运维架构 > 网站架构

gatsby_如何为Gatsby网站启用离线模式

2020-08-20 13:23 585 查看

gatsby

One of the reasons we create JAMstack sites is because of their great performance. Serving static files is easy and quick. But what if we upgrade the visitor's experience and make the site available offline?

我们创建JAMstack站点的原因之一是由于其出色的性能。 提供静态文件非常简单快捷。 但是,如果我们提升访问者的体验并使网站可以离线使用该怎么办?

Looking at both recent reports on the State of the JAMstack in 2020 (you can check out Kontent's report and Netlify's report) it's clear that performance is the main reason we are building static sites.

查看有关2020年JAMstack状况的两个最新报告(您可以查看Kontent的报告Netlify的报告 ),很明显,性能是我们构建静态站点的主要原因。

I call this fact a bit of a cheat. Performance benefit comes with the JAMstack by design, so it's like calling puppies cute. They're always cute because they're puppies.

我称这个事实有点作弊。 性能优势是设计使然的JAMstack附带的,因此就像将幼犬称为可爱。 它们总是很可爱,因为它们是小狗。

If we're really serious about performance, though, even JAMstack sites can do better. But before we can dive into offline mode for Gatsby, we must understand how Gatsby serves pages:

但是,如果我们真的非常重视性能,那么即使JAMstack网站也可以做得更好。 但是,在我们进入Gatsby的离线模式之前,我们必须了解Gatsby如何提供网页:

The visitor does not request every single HTML file from the server. Rather, Gatsby's JS client asks the server for the page-data.json of the respective page. That's how the visitor transitions into the requested page without that classic page reload. But even for that we need the network.

访问者不会从服务器请求每个HTML文件。 相反,Gatsby的JS客户端向服务器询问相应页面的page-data.json 。 这就是访问者如何在不重新加载经典页面的情况下过渡到请求的页面的方式。 但是即使如此,我们也需要网络。

为什么网站甚至需要离线模式? (Why do websites even need an offline mode?)

These days, everyone is online, right? An internet connection in mobile phones no longer seems like an option, but a requirement. We use apps like Whatsapp, Messenger, and others all the time.

这些天,每个人都在线,对吗? 移动电话中的Internet连接似乎不再是一种选择,而是必要条件。 我们一直在使用诸如Whatsapp,Messenger等应用程序。

But what if we step inside an elevator? What if we're walking to a car parked in an underground garage or driving through a tunnel? What if we're inside a plane that's about to take off?

但是,如果我们走进电梯怎么办? 如果我们要步行到停在地下车库中的汽车或通过隧道开车怎么办? 如果我们在即将起飞的飞机内怎么办?

No reception. That's what all these places share. And the only thing people can do with their phones without reception is to watch downloaded Netflix movies. Until you enable offline mode for your website.

没有接待。 这就是所有这些地方共享的东西。 人们只能在不接收电话的情况下使用手机进行操作,就是观看下载的Netflix电影。 直到您为网站启用离线模式。

它是如何工作的? (How does it work?)

In a nutshell, we save the visitor the round-trip to the server and download all the necessary data in advance. And we install a ServiceWorker which acts as a server instead of a real remote server.

简而言之,我们将访问者的往返行程保存到服务器,并预先下载所有必要的数据。 然后,我们安装了一个ServiceWorker,它充当服务器而不是真正的远程服务器。

A ServiceWorker is a script that the visitor's browser runs in the background and enables features like push notifications and others. See Google docs for more information.

ServiceWorker是一个脚本,访问者的浏览器在后台运行,并启用推式通知等功能。 有关更多信息,请参见Google文档

With Gatsby, just like we're all used to, it's as simple as installing a plugin:

使用Gatsby,就像我们都已经习惯了一样,就像安装插件一样简单:

npm i gatsby-offline-plugin --save

And adding it to the

gatsby-config.js
:

并将其添加到

gatsby-config.js

plugins: [
...
`gatsby-plugin-offline`,
...
]

But every website uses many different types of assets, so typically, we need to take one additional step and configure the service worker.

但是每个网站都使用许多不同类型的资产,因此通常,我们需要采取另一步骤并配置服务工作者。

资产服务策略 (Assets serving strategies)

Every website contains many assets ranging from CSS files through images and icons to web fonts and actual page data.

每个网站都包含许多资产,从CSS文件到图像和图标,再到网络字体和实际页面数据。

The service worker cannot really download all these assets during the first page load as that would go directly against the performance benefit. Visitors would also not be happy if their browsers started downloading 100MB of images the moment they decided to visit your photo gallery.

服务人员无法真正在首页加载期间下载所有这些资产,因为这将直接损害性能。 如果访问者在决定访问您的照相馆时就开始下载100MB的图像,他们也将不满意。

We can use regular expressions to target specific files and configure the service worker to treat them appropriately. Let's take a look at the available strategies:

我们可以使用正则表达式来定位特定文件,并配置服务工作者以适当对待它们。 让我们看一下可用的策略:

缓存优先 (CacheFirst)

Typical use: web fonts, stylesheets

典型用途:网络字体,样式表

The service worker checks the cache for the requested file. If the file's missing, it goes online to fetch it while storing it in the cache for future use.

服务人员检查高速缓存中是否包含请求的文件。 如果文件丢失,它将在线获取以将其存储在缓存中以备将来使用。

仅缓存 (CacheOnly)

Possible use: your own pre-caching logic

可能的用途:您自己的预缓存逻辑

The service worker checks the cache for the requested file. If the file's missing, it returns an error.

服务人员检查高速缓存中是否包含请求的文件。 如果文件丢失,则返回错误。

网络第一 (NetworkFirst)

Typical use: non-critical API requests

典型用途:非关键API请求

The service worker goes online to fetch the requested file. If the network is down or server unresponsive, it falls back to the cache.

服务人员上线以获取请求的文件。 如果网络中断或服务器无响应,它将回退到缓存。

仅网络 (NetworkOnly)

Typical use: critical API requests

典型用途:关键API请求

The service worker goes online to fetch the requested file. If the network is down or server unresponsive, it returns an error.

服务人员上线以获取请求的文件。 如果网络中断或服务器无响应,则返回错误。

StaleWhileRevalidate (StaleWhileRevalidate)

Typical use: front-end assets, images

典型用途:前端资产,图像

The service worker checks the cache for the requested file and provides it. Subsequently, it makes a network request to silently update the cache.

服务工作者检查高速缓存中是否有请求的文件并提供它。 随后,它发出网络请求以静默方式更新缓存。

配置盖茨比网站 (Configuring the Gatsby site)

A simple configuration of a Gatsby site that should work offline looks like this:

一个可以脱机工作的Gatsby网站的简单配置如下所示:

{
resolve: `gatsby-plugin-offline`,
options: {
precachePages: [`/blog/*`],
},
}

This way I'm configuring the service worker to pre-cache all blog posts, which are all pages whose URL starts with

/blog/
.

这样,我将服务工作者配置为预先缓存所有博客文章,这些博客文章都是URL以

/blog/
开头的所有页面。

Once the visitor accesses the index page with links to blog posts, they will be able to click-through to any of them without an active internet connection. That is, if you use the

Link
element in the implementation. Standard anchor tags make a browser go around the service worker and fetch data from remote.

一旦访问者访问带有博客文章链接的索引页面,他们就可以在没有活动的Internet连接的情况下点击进入其中的任何文章。 也就是说,如果在实现中使用

Link
元素。 标准锚标记使浏览器可以绕过服务人员,并从远程获取数据。

The service worker will treat all assets according to its default configuration:

服务人员将根据其默认配置处理所有资产:

  • CacheFirst

    缓存优先

    JS files, CSS files, everything inside folder "static/"

    JS文件,CSS文件以及文件夹“ static /”中的所有内容

  • NetworkFirst

    网络第一

    */page-data/*/page-data.json files

    * / page-data / * / page-data.json文件

  • StaleWhileRevalidate

    StaleWhileRevalidate

    images, web font files, etc.

    图片,网络字体文件等。

So if you're worried that the service worker will fetch all assets of all blog posts, it will do so only after the visitor actually opens the blog post page.

因此,如果您担心服务工作者会获取所有博客文章的所有资产,那么只有在访问者实际打开博客文章页面之后,它才会这样做。

The reason is, cache space and the visitor's internet connection bandwidth are limited. On the first page load, the visitor downloads all the site-wide assets like stylesheets, web fonts, icons, and others, so these assets will be available in the cache on subsequent loads. Images and other resources of pre-cached pages will be resolved once the page is requested and this can be changed only via custom logic.

原因是缓存空间和访问者的Internet连接带宽受到限制。 在第一页加载时,访问者会下载所有站点范围内的资产,例如样式表,Web字体,图标等,因此这些资产在后续加载时将在缓存中可用。 请求页面后,将解析预缓存页面的图像和其他资源,并且只能通过自定义逻辑进行更改。

So in which cases would you want to change the config? There were actually not many cases I could come up with, but I did stumble upon a few:

那么在哪种情况下您想更改配置? 实际上,我可以提出的案例并不多,但我确实偶然发现了一些案例:

  • Assets provided from URLs without matching filename suffix

    URL提供的资产没有匹配的文件名后缀

    Google serves CSS definitions of web fonts without the .css suffix and that is already covered by the default config. However, you may be serving images or other assets from URLs that don't have the appropriate suffix.

    Google提供不带.css后缀的Web字体CSS定义,并且默认配置已包含该定义。 但是,您可能是通过没有适当后缀的URL提供图像或其他资源的。

  • Gain more control over the cache

    更好地控制缓存

    With some assets you want to be in charge of how long a certain item can reside in cache until it becomes expired.

    对于某些资产,您要负责某个项目可以保留多长时间,直到它过期。

  • Exotic assets

    异国资产

    Alright, exotic may be a bit strong word :-) but web fonts in EOT format, pictures in HEIC format, short videos, songs, etc.

    好吧,异国情调可能是个好词:-),但是EOT格式的网络字体,HEIC格式的图片,短视频,歌曲等。

In these cases you need to adjust the default configuration and define it within the plugin options:

在这些情况下,您需要调整默认配置并在插件选项中定义它:

{
resolve: `gatsby-plugin-offline`,
options: {
precachePages: [`/blog/*`],
runtimeCaching: [
// previous definitions from the default config
(...),
{
urlPattern: /^https:\/\/fonts\.gstatic\.com/,
handler: 'cacheFirst',
options: {
cacheableResponse: {
statuses: [0, 200]
},
cacheName: 'google-fonts-webfonts',
expiration: {
maxAgeSeconds: 60 * 60,
maxEntries: 30
}
}
},
]
},
},

This additional config item will ensure that at most 30 Google fonts served from gstatic.com will be cached for a maximum duration of one hour and will be handled using the CacheFirst strategy.

这个额外的配置项将确保gstatic.com提供的最多30种Google字体将被高速缓存最长一小时,并将使用CacheFirst策略进行处理。

测试前先建立网站 (Build the Site Before Testing)

Once you are finished with the configuration, make sure to build and serve the site before testing the offline capabilities. They don't work in development mode.

完成配置后,请在测试脱机功能之前确保构建并服务该站点。 它们不在开发模式下工作。

gatsby build && gatsby serve

JAMstack =性能,但是... (JAMstack = performance, but...)

In this article I showed you how to install and configure the offline plugin for Gatsby.

在本文中,我向您展示了如何为Gatsby安装和配置脱机插件。

All JAMstack sites come with the great benefit of amazing performance by design. By adding offline capabilities, you are taking the browsing experience of your visitors to the next level compared to other JAMstack sites. The service worker configuration allows you to further fine-tune how each asset will be handled and cached.

所有JAMstack网站都具有设计惊人的性能的巨大优势。 通过添加脱机功能,与其他JAMstack网站相比,您可以将访问者的浏览体验提升到一个新的水平。 服务工作者配置使您可以进一步调整如何处理和缓存每个资产。

If you're interested, you can find more information about the plugin in the Gatsby docs.

如果您有兴趣,可以在Gatsby docs中找到有关该插件的更多信息。

翻译自: https://www.freecodecamp.org/news/how-to-enable-offline-mode-for-gatsby-site/

gatsby

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐