-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathappcache-nanny.js
427 lines (365 loc) · 11.2 KB
/
appcache-nanny.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// appCacheNanny
// =============
//
// Teaches your applicationCache some manners! Because, you know,
// http://alistapart.com/article/application-cache-is-a-douchebag
//
/* global define, applicationCache, addEventListener, localStorage */
'use strict'
;(function (root, factory) {
var appCache = (typeof applicationCache === 'undefined') ? undefined : applicationCache
// based on https://github.com/allouis/minivents/blob/main/minivents.js
function Events () {
var events = {}
var api = this
// listen to events
api.on = function on (type, func, ctx) {
if (!events[type]) (events[type] = [])
events[type].push({f: func, c: ctx})
}
// stop listening to event / specific callback
api.off = function off (type, func) {
var list = events[type] || []
var i = list.length = func ? list.length : 0
while (i-- > 0) {
if (func === list[i].f) list.splice(i, 1)
}
}
// send event, callbacks will be triggered
api.trigger = function trigger () {
var args = Array.apply([], arguments)
var list = events[args.shift()] || []
var i = list.length
var j
for (j = 0; j < i; j++) {
list[j].f.apply(list[j].c, args)
}
}
// aliases
api.bind = api.on
api.unbind = api.off
api.emit = api.trigger
}
if (typeof define === 'function' && define.amd) {
define([], function () {
root.appCacheNanny = factory(appCache, Events)
return root.appCacheNanny
})
} else if (typeof exports === 'object') {
module.exports = factory(appCache, Events)
} else {
root.appCacheNanny = factory(appCache, Events)
}
})(this, function (applicationCache, Events) {
var DEFAULT_MANIFEST_LOADER_PATH = '/appcache-loader.html'
var DEFAULT_CHECK_INTERVAL = 30000
var appCacheNanny = new Events()
var nannyOptions = {
loaderPath: DEFAULT_MANIFEST_LOADER_PATH,
checkInterval: DEFAULT_CHECK_INTERVAL,
offlineCheckInterval: DEFAULT_CHECK_INTERVAL
}
var iframe
var setupDone = false
var setupPending = false
//
//
//
appCacheNanny.isSupported = function isSupported () {
return !!applicationCache
}
//
// request the appcache.manifest file and check if there's an update
//
appCacheNanny.update = function update () {
trigger('update')
if (!setupDone) {
setupCallbacks.push(appCacheNanny.update)
if (!setupPending) {
setup()
setupPending = true
}
return true
}
if (!appCacheNanny.isSupported()) {
return false
}
try {
applicationCache.update()
return true
} catch (e) {
// there might still be cases when ApplicationCache is not support
// e.g. in Chrome, when returned HTML is status code 40X, or if
// the applicationCache became obsolete
appCacheNanny.update = noop
return false
}
}
//
// start auto updating. Optionally pass interval in ms to
// overwrite the current.
//
var intervalPointer
appCacheNanny.start = function start (options) {
if (options) appCacheNanny.set(options)
if (!setupDone) {
setupCallbacks.push(appCacheNanny.start)
if (!setupPending) {
setup()
setupPending = true
}
return true
}
clearInterval(intervalPointer)
// check with offline interval
checkInterval = hasNetworkError ? appCacheNanny.get('offlineCheckInterval') : appCacheNanny.get('checkInterval')
intervalPointer = setInterval(appCacheNanny.update, checkInterval)
isCheckingForUpdatesFlag = true
trigger('start')
}
//
// stop auto updating
//
appCacheNanny.stop = function stop () {
if (!isCheckingForUpdatesFlag) return
clearInterval(intervalPointer)
isCheckingForUpdatesFlag = false
trigger('stop')
}
//
// returns true if the nanny is checking periodically for updates
//
appCacheNanny.isCheckingForUpdates = function isCheckingForUpdates () {
return isCheckingForUpdatesFlag
}
//
// returns true if an update has been fully received, otherwise false
//
appCacheNanny.hasUpdate = function hasUpdate () {
return hasUpdateFlag
}
//
//
//
appCacheNanny.set = function setOption (key, value) {
var property, newSettings
if (typeof key === 'object') {
newSettings = key
for (property in newSettings) {
if (newSettings.hasOwnProperty(property)) {
nannyOptions[property] = newSettings[property]
}
}
return
}
nannyOptions[key] = value
}
//
//
//
appCacheNanny.get = function getOption (key) {
var property
var settings = {}
if (key) {
return nannyOptions[key]
}
for (property in nannyOptions) {
if (nannyOptions.hasOwnProperty(property)) {
settings[property] = nannyOptions[property]
}
}
return settings
}
// Private
// -------
// this is the internal state of checkInterval.
// It usually differs between online / offline state
var checkInterval = DEFAULT_CHECK_INTERVAL
// flag if there is a pending update, being applied after next page reload
var hasUpdateFlag = false
// flag whether the nanny is checking for updates in the background
var isCheckingForUpdatesFlag = false
// flag if there was an error updating the appCache, usually meaning
// it couldn't connect, a.k.a. you're offline.
var hasNetworkError = false
//
var isInitialDownload = false
//
// setup appCacheNanny
//
var noop = function () {}
var APPCACHE_STORE_KEY = '_appcache_nanny'
var setupCallbacks = []
function setup () {
var scriptTag
try {
isInitialDownload = !localStorage.getItem(APPCACHE_STORE_KEY)
localStorage.setItem(APPCACHE_STORE_KEY, '1')
} catch (e) {}
if (!appCacheNanny.isSupported()) {
appCacheNanny.update = noop
return
}
// https://github.com/gr2m/appcache-nanny/issues/7
if (applicationCache.status !== applicationCache.UNCACHED) {
subscribeToEvents()
setupPending = false
setupDone = true
setupCallbacks.forEach(function (callback) {
callback()
})
return
}
// load the appcache-loader.html using an iframe
iframe = document.createElement('iframe')
iframe.src = nannyOptions.loaderPath
iframe.style.display = 'none'
iframe.onload = function () {
// we use the iFrame's applicationCache Object now
applicationCache = iframe.contentWindow.applicationCache
subscribeToEvents()
setupPending = false
setupDone = true
// adding a timeout prevented Safari 7.1.4 from throwing
// a InvalidStateError on the first applicationCache.update() call
setTimeout(function () {
setupCallbacks.forEach(function (callback) {
callback()
})
}, 100)
}
iframe.onerror = function () {
throw new Error('/appcache-loader.html could not be loaded.')
}
scriptTag = document.getElementsByTagName('script')[0]
scriptTag.parentNode.insertBefore(iframe, scriptTag)
}
//
//
//
function subscribeToEvents () {
// Fired when the manifest resources have been downloaded.
on('updateready', handleUpdateReady)
// fired when manifest download request failed
// (no connection or 5xx server response)
on('error', handleNetworkError)
// fired when manifest download request succeeded
// but server returned 404 / 410
on('obsolete', handleNetworkObsolete)
// fired when manifest download succeeded
on('noupdate', handleNetworkSuccess)
on('cached', handleNetworkSuccess)
on('progress', handleNetworkSuccess)
on('downloading', handleNetworkSuccess)
// when browser goes online/offline, look for updates to make sure.
addEventListener('online', appCacheNanny.update, false)
addEventListener('offline', appCacheNanny.update, false)
}
//
// interface to bind events to cache events
//
function on (eventName, callback) {
applicationCache.addEventListener(eventName, callback, false)
}
//
// Trigger event on appCacheNanny. Once an update is ready, we
// keep looking for another update, but we stop triggering events.
//
function trigger (eventName, event) {
if (hasUpdateFlag) return
appCacheNanny.trigger(eventName, event)
}
//
//
//
var pendingUpdateReady = false
function handleUpdateReady () {
// Safari and Firefox (in private mode) can get into an invalid
// applicationCache state, which throws an InvalidStateError error
// on applicationCache.swapCache(). To workaround that, we reset
// everything and set a flag that the next "noupdate" event, that
// will now be triggered when the iframe gets reloadd, is actually
// an "updateready" event.
if (applicationCache.status !== applicationCache.UPDATEREADY) {
pendingUpdateReady = true
reset()
return
}
if (!hasUpdateFlag) {
hasUpdateFlag = true
// don't use trigger here, otherwise the event wouldn't get triggered
appCacheNanny.trigger('updateready')
}
applicationCache.swapCache()
}
//
//
//
function handleNetworkSuccess (event) {
var prefix = ''
// when page gets opened for the very first time, it already has
// the correct assets, but appCache still triggers 'downloading',
// 'progress' and 'cached' events. Once the first 'cached' event
// gets triggered, all assets are cached offline. We prefix these
// initial events with 'init:'
if (isInitialDownload) {
prefix = 'init:'
if (event.type === 'cached') {
isInitialDownload = false
}
}
// re-trigger event via appCacheNanny
if (pendingUpdateReady) {
trigger('updateready')
pendingUpdateReady = false
} else {
trigger(prefix + event.type, event)
}
if (!hasNetworkError) return
hasNetworkError = false
appCacheNanny.start()
trigger('online')
}
//
//
//
function handleNetworkError (error) {
// re-trigger event via appCacheNanny
trigger('error', error)
if (hasNetworkError) return
hasNetworkError = true
// Edge case: private mode in Safari & FF say they support applicationCache,
// but they fail. To get arround that, we only trigger the offline event
// when applicationCache.status != uncached
if (applicationCache.status === applicationCache.UNCACHED) return
appCacheNanny.start()
trigger('offline')
}
//
// The 'obsolete' event gets triggered if the requested *.appcache file
// has been removed or renamed. The intent behind renaming an *.appcache
// file is to clear all locally cached files, it's the only way to do so.
// Therefore we don't treet it as an error, it usually means that there
// is an update availble that becomes visible after the next page reload.
//
function handleNetworkObsolete () {
// re-trigger event via appCacheNanny
trigger('obsolete')
if (hasNetworkError) {
hasNetworkError = false
trigger('online')
}
// Once applicationCache status is obsolete, calling .udate() throws
// an error, so we stop checking here
appCacheNanny.stop()
}
function reset () {
if (iframe) {
iframe.remove()
}
setupDone = false
setupPending = false
appCacheNanny.update()
}
return appCacheNanny
})