0
# Simple Setup Functions
1
2
High-level functions for quick precaching setup that handle the most common use cases. These functions provide an easy way to get started with precaching without needing to understand the underlying implementation details.
3
4
## Capabilities
5
6
### Precache and Route
7
8
The most commonly used function that combines precaching assets and setting up request routing in a single call.
9
10
```typescript { .api }
11
/**
12
* Adds items to the precache list and adds a route to respond to fetch events
13
* @param entries - Array of entries to precache (PrecacheEntry objects or URL strings)
14
* @param options - Optional route configuration options
15
*/
16
function precacheAndRoute(
17
entries: Array<PrecacheEntry | string>,
18
options?: PrecacheRouteOptions
19
): void;
20
```
21
22
**Usage Examples:**
23
24
```typescript
25
import { precacheAndRoute } from "workbox-precaching";
26
27
// Basic usage with mixed entry types
28
precacheAndRoute([
29
// PrecacheEntry with revision for cache busting
30
{ url: "/index.html", revision: "abc123" },
31
{ url: "/styles.css", revision: "def456" },
32
33
// String URLs (use URL as cache key)
34
"/static/logo.png",
35
"/api/data.json",
36
37
// Entry with integrity for security
38
{
39
url: "/critical.js",
40
revision: "xyz789",
41
integrity: "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
42
}
43
]);
44
45
// With route options
46
precacheAndRoute([
47
{ url: "/app.html", revision: "v1.2.3" }
48
], {
49
// Serve /app.html for directory requests like /dashboard/
50
directoryIndex: "app.html",
51
52
// Ignore tracking parameters when matching URLs
53
ignoreURLParametersMatching: [/^utm_/, /^fbclid$/],
54
55
// Try .html extension for clean URLs
56
cleanURLs: true
57
});
58
```
59
60
### Precache
61
62
Adds items to the precache list for installation during the service worker install event. Does not set up request routing.
63
64
```typescript { .api }
65
/**
66
* Adds items to the precache list and stores them during service worker install.
67
* Note: Only precaches files - does not serve them. Use addRoute() to serve cached files.
68
* @param entries - Array of entries to precache (PrecacheEntry objects or URL strings)
69
*/
70
function precache(entries: Array<PrecacheEntry | string>): void;
71
```
72
73
**Usage Examples:**
74
75
```typescript
76
import { precache, addRoute } from "workbox-precaching";
77
78
// Precache assets without setting up routing
79
precache([
80
"/offline.html",
81
"/fallback.css",
82
{ url: "/app-shell.html", revision: "v2.1.0" }
83
]);
84
85
// Later, set up routing separately
86
addRoute({
87
cleanURLs: true,
88
directoryIndex: "app-shell.html"
89
});
90
```
91
92
### Add Route
93
94
Adds a fetch event listener to the service worker that responds to network requests with precached assets.
95
96
```typescript { .api }
97
/**
98
* Adds a fetch listener to the service worker that responds to network requests with precached assets.
99
* Must be called after precache() to serve the precached resources.
100
* @param options - Optional configuration options for the precache route
101
*/
102
function addRoute(options?: PrecacheRouteOptions): void;
103
```
104
105
**Usage Examples:**
106
107
```typescript
108
import { precache, addRoute } from "workbox-precaching";
109
110
// First, precache the assets
111
precache([
112
"/index.html",
113
"/about.html",
114
"/contact.html"
115
]);
116
117
// Then add routing with custom options
118
addRoute({
119
// Custom directory index
120
directoryIndex: "index.html",
121
122
// Ignore search parameters
123
ignoreURLParametersMatching: [/^ref$/, /^campaign$/],
124
125
// Enable clean URLs (serve /about.html for /about)
126
cleanURLs: true,
127
128
// Custom URL manipulation for additional URL variants
129
urlManipulation: ({ url }) => {
130
// Also try with trailing slash
131
if (!url.pathname.endsWith('/')) {
132
const newUrl = new URL(url);
133
newUrl.pathname += '/';
134
return [newUrl];
135
}
136
return [];
137
}
138
});
139
```
140
141
## Route Options
142
143
```typescript { .api }
144
interface PrecacheRouteOptions {
145
/** Default file for directory requests (default: 'index.html') */
146
directoryIndex?: string;
147
148
/** URL parameters to ignore when matching (default: [/^utm_/, /^fbclid$/]) */
149
ignoreURLParametersMatching?: RegExp[];
150
151
/** Whether to try .html extension for clean URLs (default: true) */
152
cleanURLs?: boolean;
153
154
/** Custom URL manipulation function for generating additional URL variations */
155
urlManipulation?: urlManipulation;
156
}
157
158
/**
159
* Callback function for generating additional URL variations to check against precached files
160
* @param context - Object containing the request URL
161
* @returns Array of additional URLs to check (should be URL objects, not strings)
162
*/
163
type urlManipulation = ({ url }: { url: URL }) => URL[];
164
```
165
166
## Entry Types
167
168
```typescript { .api }
169
interface PrecacheEntry {
170
/** URL to precache */
171
url: string;
172
173
/** Revision information for cache busting (if null, uses URL as cache key) */
174
revision?: string | null;
175
176
/** Integrity metadata for network request validation */
177
integrity?: string;
178
}
179
```
180
181
## Common Patterns
182
183
### Generated Manifest
184
185
Most build tools generate a manifest of assets with revisions:
186
187
```typescript
188
import { precacheAndRoute } from "workbox-precaching";
189
190
// Usually generated by build tools like Workbox CLI or webpack plugin
191
const precacheManifest = [
192
{ url: "/index.html", revision: "a1b2c3" },
193
{ url: "/styles.css", revision: "d4e5f6" },
194
{ url: "/script.js", revision: "g7h8i9" }
195
];
196
197
precacheAndRoute(precacheManifest);
198
```
199
200
### Mixed Assets
201
202
Combine generated and static assets:
203
204
```typescript
205
import { precacheAndRoute } from "workbox-precaching";
206
207
precacheAndRoute([
208
// Generated assets with revisions
209
...self.__WB_MANIFEST,
210
211
// Static assets (use URL as cache key)
212
"/images/logo.png",
213
"/fonts/custom.woff2"
214
]);
215
```