当前位置:网站首页>Serviceworker cache and HTTP cache
Serviceworker cache and HTTP cache
2022-04-21 21:49:00 【Cloud smart aiops community】
author :JerryC
although ServiceWorker and PWA Is becoming a modern Web Application standards , But browser resource caching has become more complex than ever .
This article covers the key content of browser caching , Specific include :
- ServiceWorker Caching and HTTP Cache priority ?
- Implemented by mainstream browsers MemoryCache and DiskCache On which floor ?
- MemoryCache、DiskCache、ServiceWorker Which cache is faster ?
Cache process overview
Let's first look at the order of resource requests defined by the standard :
- ServiceWorker cache :ServiceWorker Check whether the resource exists in its cache , And decide whether to return resources according to its programmed cache strategy . This operation will not happen automatically , Need to register in ServiceWorker In the definition of
fetchEvent to intercept and process network requests , So you can hit ServiceWorker Cache, not the network or HTTP cache . - HTTP cache : Here is what we often say 「 Strong cache 」 and 「 Negotiate the cache 」, If HTTP If the cache has not expired , The browser will use HTTP Cached resources .
- Server side : If ServiceWorker Caching or HTTP No resources found in cache , The browser requests resources from the network . This will involve CDN The work of the service or source service .
This is the standard defined resource request process , But browsers with pursuit will still be in ServiceWorker Add a layer on top 「 Memory cache layer 」 , With Chrome For example , We request a resource , Remove the network , There are three browser caches that return :
that MemoryCache and DiskCache And ServiceWorker Cache What is your priority ?
Now let's talk about the differences between the three .
MemoryCache、DiskCache At which layer of the cache process ?
We use Chrome For example ,MemoryCache As a first citizen , be located ServiceWorker above .
That is, hit MemoryCache, It won't trigger ServiceWorker Of fetch event .
and DiskCache Is located in the original HTTP Cache layer :
MemoryCache The existence of can lead to a problem : ServiceWorker You don't always have control over resources . This will make the situation we had expected complex and unpredictable . It is a pity MemoryCache It's not in W3C In the standard of ,W3C from 2016 This matter is still being discussed in , It seems that this problem cannot be solved in a short time .
Some topics under discussion :
- safari fetches from memory cache instead of Service worker
- Difference between disk and memory cache
- Advanced Questions About Service Worker
- allow service worker produced resources to be marked as "cachable"
Is there really nothing we can do ?
If we encounter a business scenario , Indeed. ServiceWorker There are strong requirements for resource control , We can still do something .
MemoryCache Is controlled by 「 Strong cache 」 Of , This means that we can be in ServiceWorker Intercept the response of the resource , And set the resource response header to make the resource from MemoryCache invalid :
cache-control: max-age=0
Copy code
self.addEventListener("fetch", (event) => {
event.respondWith(
(async function () {
// from HTTP Cache or network access resources
const res = fetch(event.request);
// because Response Is a stream , It can only be used once , So here it is clone once .
const newRes = res.clone();
// Rewrite the resource response header
return new Response(res.body, { ...newRes, headers: {
'cache-control': 'max-age=0'
}});
})();
);
});
Copy code
It should be noted that , This method is based on the premise of sacrificing a small amount of loading performance . It depends on the performance priority in our actual scenario , Or offline first , Or whatever else is preferred .
MemoryCache、DiskCache、ServiceWorker Which cache is faster ?
Let's take another look at the loading speed and priority of three caches of the same resource :
- Loading speed :MemoryCache > DiskCache > ServiceWorker
- priority :MemoryCache > ServiceWorker> DiskCache
MemoryCache The priority is ServiceWorker front , This is OK .
But slower ServiceWorker Priority is faster than speed DiskCache Higher ?
That dish down ,ServiceWorker Isn't it slowing down the loading speed of the site ?
Controlled experiment
To study the problem , I did a set of controlled experiments .
The experiment is only in Chrome Conduct ,chrome devtool Provide time for each resource . All information about loading resources can be used as HAR Download the file , Then write a local script for information extraction and Analysis .
experimental condition
The same environment :Chrome97 / MacOS 10.14 / Wifi
Multiple concurrent loading of the same picture :
- 3 Zhang 133KB picture 10 Experiments
- 10 Zhang 133KB picture 10 Experiments
- 100 Zhang 133KB picture 10 Experiments
Observe two properties :
- DiskCache Cache performance
- ServiceWorker Cache speed performance
Experiment 1 :3 Zhang 133KB Picture concurrency
The first is concurrent requests 3 Picture for 10 Experiments , Take the average data , Then observe DiskCache、ServiceWorker Cache Performance of .
Observe :
- DiskCache: We found that the download operation didn't take much time , But resources are waiting in line .
- ServiceWorker Cache: More time-consuming downloading .
Conclusion : But nonetheless , In this case , DiskCache Still better than ServiceWorker Cache faster .
Experiment two :3 Zhang 133KB picture 10 Experiments
When I add concurrent images to 10 Zhang , This situation may be closer to the actual situation , There may be more different resources in the site (JS file 、 typeface 、 style 、 Image, etc ), Because some websites may have more than one page 10 A resource .
Observe :
- DiskCache: The queue time from the second resource is still very long , But the download time is basically the same .
- ServiceWorker Cache: Queuing is not a problem , But waiting is .
Conclusion : In this case , DiskCache Will be slightly inferior to ServiceWorker Cache.
Experiment three :3 Zhang 133KB picture 100 Experiments
When I add concurrent images to 100 Zhang , This situation is almost untrue , But I wonder why DiskCache Why in the first experiment than ServiceWorker Cache faster .
Observe :
- DiskCache: Queuing is still a problem , And with the number of concurrency increases linearly . We can even see how the browser loads images , One concurrency is about 6 A picture .
- ServiceWorker Cache: Although the waiting time increases with the number of concurrency , But it's gentle .
Conclusion : At the same time ServiceWorker Cache Than DiskCache faster .
that DiskCache and ServiceWorker How to choose ? Children make choices , Adults have to
because ServiceWorker The priority is DiskCache above , We can do it in ServiceWorker Conduct 「 Resource race 」, Request at the same time ServiceWorker Cache and DiskCache, Which one returns first will return the resource to the upper layer . The code might look like this :
self.addEventListener("fetch", (event) => {
event.respondWith(
(async function () {
const res = Promise.race([
// request ServiceWorker Cache
cache.open(CACHE_NAME).then(cache => cache.match(event.request)),
// request DiskCache Or network resources
fetch(event.request)
])
})();
);
});
Copy code
Experiment four : After the resource race , Concurrent request 3 A picture 、10 A picture and 100 A picture
When we race for resources , In this case , Whether it's a small amount of concurrent resources or a large amount of resources , Can reach the fastest level .
summary
In this article, we understand ServiceCache、MemoryCache、DiskCache The priority of the .
Then I made an in-depth comparison ServiceWorker Cache and DiskCache Performance of .
When a small amount of resources are concurrent ,DiskCache faster , When a large number of resources are concurrent ,ServiceWorker faster .
Finally through 「 Resource race 」 To take into account both situations .
however , At some point , We compare ServiceWorker and HTTP Caching is a little unfair .
ServiceWorker Will be more widely used , It provides finer cache control 、 Make the application offline 、 And compare the main thread , He can use more CacheAPI Capacity .
At the end
In recent years , stay AIOps In the context of the rapid development of the field ,IT Tools 、 Platform capabilities 、 Solution 、AI The urgent need for scenarios and available data sets burst out in various industries . Based on this , Cloud wisdom is 2021 year 8 Month issued AIOps Community , It aims to set up a banner of open source , For customers in various industries 、 user 、 Researchers and developers build an active user and developer community , Jointly contribute and solve industry problems 、 Promote technological development in this field .
The community has ** Open source A data visualization layout platform -FlyFish、 Operation and maintenance management platform OMP、 Cloud service management platform - Moore platform 、Hours** Algorithms and other products .
Visual editing platform -FlyFish:
- Flying fish demo address
- Github Project address
- Gitee Project address
- 15 A large screen case of the industry
Some large screen cases :
版权声明
本文为[Cloud smart aiops community]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204212144443822.html
边栏推荐
- 细粒度情感分析实战
- Mongo geonear query Chinese fuzzy search in PHP
- Summary of force deduction method 824 - goat Latin
- 外包学生管理系统的架构文档
- avformat_ new_ Stream understanding
- 【编程时适合的音乐】
- 力扣解法汇总824-山羊拉丁文
- Architecture document of outsourcing student management system
- Analysts believe that Samsung Galaxy Z fold 4 and Z flip 4 may be cheaper than their previous products
- FFmpeg连载1-环境搭建
猜你喜欢
随机推荐
mysql 模糊搜索与校对规则
Ffmpeg serial 3-video decoding
AI应用说-生产制造专场(配件安装质检)
[UML operation contract]
mybtais的mapper中使用@Select注解使用if
Online yaml to properties tool
Eeasybi report system data source selection code development manual
MSWEP数据nc格式转tif格式
在线YAML转Properties工具
微服务,中台,RPA和低代码火热背后的一些冷思考
[summary of the most complete bat must ask high concurrency in history]
【题解】[SDOI2012] 吊灯
[use case level definition]
一加连发两款耳机产品:充电10分钟 听歌20小时
How to set the South parameter when streaming from libvlc library
分析师认为三星Galaxy Z Fold 4和Z Flip 4可能比其前代产品更便宜
Mswep data NC format to TIF format
UML integrated design example
移动Web开发之rem实际开发适配方案
LU分解、LDLT分解和Cholesky分解_zjuzly的博客-CSDN博客_ldlt









