3
<title>Cache Expiration Demo</title>
4
<link rel="stylesheet" href="../common.css">
5
<link rel="stylesheet" href="styles.css">
7
// If we're running on a real web server (as opposed to localhost, which is whitelisted),
8
// then change the protocol to HTTPS.
9
// See https://goo.gl/lq4gCo for an explanation as to why this is needed for some features.
11
var isLocalhost = !!(window.location.hostname === 'localhost' ||
12
// [::1] is the IPv6 localhost address.
13
window.location.hostname === '[::1]' ||
14
// 127.0.0.1/8 is considered localhost for IPv4.
15
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/));
16
if (window.location.protocol === 'http:' && !isLocalhost) {
17
// Redirect to https: if we're currently using http: and we're not on localhost.
18
window.location.protocol = 'https:';
25
<h1>Cache Expiration Demo</h1>
29
The <a href="service-worker.js" target="_blank">service worker</a> in this example
30
demonstrates using the <code>maxCacheEntries</code> and <code>maxCacheAgeSeconds</code>
31
options. It uses a dedicated cache to hold YouTube video thumbnails. That
32
dedicated cache will purge entries once they're older than 30 seconds, and store at most 10
33
entries. It uses the <code>cacheFirst</code> strategy, so any responses that are still in the
34
cache will be used directly, without going against the network.
38
While this example uses both <code>maxCacheEntries</code> and <code>maxCacheAgeSeconds</code>,
39
it's possible to use each of those options independently.
43
The cache used for YouTube thumbnail URLs is separate from the "default" cache, which is
44
used for all other requests, like YouTube API responses and this page's CSS, JavaScript, and
45
HTML. The page doesn't impose any upper limit on the size of that default cache, and we can
46
use a <code>networkFirst</code> strategy for it.
50
Creating a dedicated cache with expiration options for dynamic, unbounded requests is a useful
51
pattern to follow. If we just used the default cache without imposing a cache expiration,
52
then that cache would grow in size as more and more searches were performed, needlessly
53
consuming disk space for old thumbnails that are likely no longer needed.
58
Try increasing the number of thumbnails returned, or changing the search term, and then
59
observe the cache expirations logged in the developer console.
62
<label for="searchTerm">Search YouTube for</label>
63
<input id="searchTerm" type="search" value="javascript">
64
<label for="maxResults">, returning at most</label>
65
<input id="maxResults" type="number" min="1" max="50" value="10">
66
<span>thumbnails.</span>
67
<input type="submit" value="Search">
70
<div id="results"></div>
72
<script src="app.js"></script>
73
<script src="../../companion.js" data-service-worker="service-worker.js"></script>