├── .gitignore ├── .jshintrc ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── README.md ├── appcache-loader.html ├── appcache-nanny.js ├── bin └── dev-server.js ├── bower.json ├── demo ├── demo.gif ├── index.html ├── manifest.appcache ├── script.js └── style.css ├── package.json └── test └── index.js /.gitignore: -------------------------------------------------------------------------------- 1 | log 2 | node_modules 3 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | /* 3 | * ENVIRONMENTS 4 | * ================= 5 | */ 6 | 7 | // Define globals exposed by modern browsers. 8 | "browser": true, 9 | 10 | // Define globals exposed by jQuery. 11 | "jquery": true, 12 | 13 | // Define globals exposed by Node.js. 14 | "node": true, 15 | 16 | /* 17 | * ENFORCING OPTIONS 18 | * ================= 19 | */ 20 | 21 | // Force all variable names to use either camelCase style or UPPER_CASE 22 | // with underscores. 23 | "camelcase": true, 24 | 25 | // Prohibit use of == and != in favor of === and !==. 26 | "eqeqeq": true, 27 | 28 | // Suppress warnings about == null comparisons. 29 | "eqnull": true, 30 | 31 | // Enforce tab width of 2 spaces. 32 | "indent": 2, 33 | 34 | // Prohibit use of a variable before it is defined. 35 | "latedef": "nofunc", 36 | 37 | // Require capitalized names for constructor functions. 38 | "newcap": true, 39 | 40 | // Enforce use of single quotation marks for strings. 41 | "quotmark": "single", 42 | 43 | // Prohibit trailing whitespace. 44 | "trailing": true, 45 | 46 | // Prohibit use of explicitly undeclared variables. 47 | "undef": true, 48 | 49 | // Warn when variables are defined but never used. 50 | "unused": false, 51 | 52 | // Enforce placing 'use strict' at the top function scope 53 | "strict": false 54 | } 55 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | cache: 4 | directories: 5 | - node_modules 6 | notifications: 7 | email: false 8 | node_js: 9 | - '4' 10 | before_install: 11 | - npm i -g npm@3 12 | before_script: 13 | - npm prune 14 | after_success: 15 | - npm run semantic-release 16 | env: 17 | matrix: 18 | - CLIENT=saucelabs:firefox:34 # pinning version, see https://code.google.com/p/selenium/issues/detail?id=8390 19 | - CLIENT=saucelabs:chrome 20 | - CLIENT=saucelabs:safari:6 21 | - CLIENT="saucelabs:iphone:8.1:OS X 10.9" 22 | - CLIENT="saucelabs:internet explorer:11:Windows 8.1" 23 | branches: 24 | except: 25 | - /^v\d+\.\d+\.\d+$/ 26 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | - Using welcoming and inclusive language 18 | - Being respectful of differing viewpoints and experiences 19 | - Gracefully accepting constructive criticism 20 | - Focusing on what is best for the community 21 | - Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | - The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | - Trolling, insulting/derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at opensource+coc@martynus.net. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [https://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: https://contributor-covenant.org 74 | [version]: https://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | The appCache Nanny 2 | ================== 3 | 4 | > Teaches the applicationCache douchebag some manners! 5 | 6 | [![Build Status](https://travis-ci.org/gr2m/appcache-nanny.svg?branch=main)](https://travis-ci.org/gr2m/appcache-nanny) 7 | [![Dependency Status](https://david-dm.org/gr2m/appcache-nanny.svg)](https://david-dm.org/gr2m/appcache-nanny) 8 | [![devDependency Status](https://david-dm.org/gr2m/appcache-nanny/dev-status.svg)](https://david-dm.org/gr2m/appcache-nanny#info=devDependencies) 9 | 10 | As we all know, the [Application Cache is a Douchebag](http://alistapart.com/article/application-cache-is-a-douchebag). 11 | It's time to teach it some manners – The appCache Nanny for Rescue! 12 | 13 | No more manifest attributes on your HTML files. Whether you want to cache 14 | your assets offline or not, when to start ... You Are In Control™ 15 | 16 | Have a glance: 17 | 18 | ```js 19 | // start to check for updates every 30s 20 | appCacheNanny.start() 21 | 22 | // optionally, pass intervals in ms 23 | appCacheNanny.start({checkInterval: 10000}) 24 | 25 | // you can also check for updates at any time 26 | appCacheNanny.update() 27 | 28 | // The appCache nanny tells you if there is a new update available 29 | appCacheNanny.hasUpdate() 30 | 31 | // She tells you about all relevant applicationCache events 32 | appCacheNanny.on('update', handleUpdate) 33 | appCacheNanny.on('error', handleError) 34 | appCacheNanny.on('obsolete', handleObsolete) 35 | appCacheNanny.on('noupdate', handleNoupdate) 36 | appCacheNanny.on('downloading', handleDownloading) 37 | appCacheNanny.on('progress', handleProgress) 38 | appCacheNanny.on('cached', handleCached) 39 | appCacheNanny.on('updateready', handleUpdateready) 40 | 41 | // plus some extra ones 42 | appCacheNanny.on('init:downloading', handleInitDownloading) 43 | appCacheNanny.on('init:progress', handleInitProgress) 44 | appCacheNanny.on('init:cached', handleInitCached) 45 | appCacheNanny.on('start', handleStart) 46 | appCacheNanny.on('stop', handleStop) 47 | 48 | // options 49 | appCacheNanny.set('loaderPath', '/path/to/my-custom-loader.html') 50 | appCacheNanny.set({ 'loaderPath': '/path/to/my-custom-loader.html' }) 51 | appCacheNanny.get('loaderPath') 52 | appCacheNanny.get() // returns all options 53 | ``` 54 | 55 | Setup 56 | ----- 57 | 58 | 1. Copy `appcache-loader.html` into the root directory of your app, 59 | so that it's accessible at `/appcache-loader.html`. 60 | 2. Create the `manifest.appcache` file and put it in the root directory 61 | of your app, next to `/appcache-loader.html`. If you use a different 62 | name, make sure to set it accordingly in `appcache-loader.html`. 63 | 64 | Then load the `appcache-nanny.js` on your HTML pages. 65 | 66 | ```html 67 | 68 | ``` 69 | 70 | If you use [bower](http://bower.io/), you can install it using: 71 | 72 | ``` 73 | bower install --save appcache-nanny 74 | ``` 75 | 76 | Or install via [npm](https://www.npmjs.com/) 77 | 78 | ``` 79 | npm install --save appcache-nanny 80 | ``` 81 | 82 | Background 83 | ---------- 84 | 85 | I extracted `appcache-nanny.js` from [minutes.io](https://minutes.io), which is an [Offline First](http://offlinefirst.org/) 86 | web application, anno 2011. It's battle tested by a ton of users, devices, internet environments. 87 | 88 | minutes.io checks every 30 seconds if an update is available. And whenever the user navigates 89 | from one view to another, it reloads the page in case there is. As the assets are all cached, 90 | the user cannot tell that their page got just reloaded. It's silent, without any notification, 91 | or a prompt asking the user to reload the page. And it works very well so far. 92 | 93 | Demo 94 | ---- 95 | 96 | ![appCacheNanny demo screencast](https://raw.github.com/gr2m/appcache-nanny/main/demo/demo.gif) 97 | 98 | The appCache Nanny comes with a simple server for testing. Start it using Node: 99 | 100 | ```js 101 | npm start 102 | ``` 103 | 104 | It will start a local server at http://localhost:8888. 105 | 106 | This is a static server with a few hidden features: 107 | 108 | - `GET /bump-version` increases the app version, so an update gets triggered 109 | on next check 110 | - `GET /remove-manifest` makes `GET /manifest.appcache` return 404, so it 111 | becomes obsolete on next check 112 | - `GET /recreate-manifest` undoes the previous step. 113 | 114 | 115 | Gotchas 116 | ------- 117 | 118 | ### Unlisted paths get loaded from the server, not from cache (via FALLBACK) 119 | 120 | Thanks to the [iframe hack](http://labs.ft.com/category/tutorial/), your HTML pages do 121 | not get added to the list of cached assets locally, and won't get checked for updates 122 | each time. Which is great especially for a Single Page Application with pushState enabled. 123 | But if your app has paths like `/welcome`, `/Dashboard`, `Meeting/123` and your `manifest.appcache` 124 | looks something like 125 | 126 | ``` 127 | CACHE MANIFEST 128 | 129 | / 130 | /app.js 131 | /styles.css 132 | 133 | FALLBACK: 134 | / / 135 | ``` 136 | 137 | Beware that opening `http://yourapp.com` will always show the currently cached 138 | version, as it is explicetly listed, while `http://yourapp.com/welcome` and 139 | other paths will load the page from the server, unless the user is offline. 140 | 141 | You might have learned that assets that are not listed in the cache manifest 142 | cannot be loaded at all, even when online. But that's not the case if the 143 | loaded HTML page does not have the `manifest` property on the `html` tag. 144 | 145 | 146 | Acknowledgement 147 | --------------- 148 | 149 | The appCache Nanny is based on tremendeous amount of research others have done 150 | on applicationCache. I'd like to highlight 151 | 152 | * **[Jake Archibald](https://twitter.com/jaffathecake)**: [Application Cache is a Douchebag](http://alistapart.com/article/application-cache-is-a-douchebag) 153 | and for some great laughs: [Network connectivity: optional](http://www.youtube.com/watch?v=Z7sRMg0f5Hk) 154 | * **[Financial Times Lab Team](http://labs.ft.com)**: [Tutorial: How to make an offline HTML5 web app](http://labs.ft.com/category/tutorial/), 155 | also recommended: [Andrew Betts – Offline rules](http://www.youtube.com/watch?v=Ut4R4udJ4Gw) 156 | * **[Eric Bidelman](https://twitter.com/ebidel)**: [A Beginner's Guide to Using the Application Cache](http://www.html5rocks.com/en/tutorials/appcache/beginner/) 157 | * [Appcache Facts](http://appcache.offline.technology/) by [Mark Christian](https://twitter.com/shinypb) & [Peter Lubbers](https://twitter.com/peterlubbers) 158 | 159 | 160 | TODOs / IDEAs 161 | ------------- 162 | 163 | * on obsolete, remove the iframe, load it again to check if a new *.appcache path 164 | has been set. If yes, update and trigger `updateready` event, otherwise trigger 165 | `obsolete` event 166 | 167 | Fine Print 168 | ---------- 169 | 170 | The appCache Nanny has been authored by [Gregor Martynus](https://github.com/gr2m), 171 | proud member of the [Hoodie Community](http://hood.ie/). 172 | 173 | License: MIT 174 | -------------------------------------------------------------------------------- /appcache-loader.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | appCache loader 6 | 7 | 8 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /appcache-nanny.js: -------------------------------------------------------------------------------- 1 | // appCacheNanny 2 | // ============= 3 | // 4 | // Teaches your applicationCache some manners! Because, you know, 5 | // http://alistapart.com/article/application-cache-is-a-douchebag 6 | // 7 | 8 | /* global define, applicationCache, addEventListener, localStorage */ 9 | 'use strict' 10 | 11 | ;(function (root, factory) { 12 | var appCache = (typeof applicationCache === 'undefined') ? undefined : applicationCache 13 | 14 | // based on https://github.com/allouis/minivents/blob/main/minivents.js 15 | function Events () { 16 | var events = {} 17 | var api = this 18 | 19 | // listen to events 20 | api.on = function on (type, func, ctx) { 21 | if (!events[type]) (events[type] = []) 22 | events[type].push({f: func, c: ctx}) 23 | } 24 | 25 | // stop listening to event / specific callback 26 | api.off = function off (type, func) { 27 | var list = events[type] || [] 28 | var i = list.length = func ? list.length : 0 29 | while (i-- > 0) { 30 | if (func === list[i].f) list.splice(i, 1) 31 | } 32 | } 33 | 34 | // send event, callbacks will be triggered 35 | api.trigger = function trigger () { 36 | var args = Array.apply([], arguments) 37 | var list = events[args.shift()] || [] 38 | var i = list.length 39 | var j 40 | for (j = 0; j < i; j++) { 41 | list[j].f.apply(list[j].c, args) 42 | } 43 | } 44 | 45 | // aliases 46 | api.bind = api.on 47 | api.unbind = api.off 48 | api.emit = api.trigger 49 | } 50 | 51 | if (typeof define === 'function' && define.amd) { 52 | define([], function () { 53 | root.appCacheNanny = factory(appCache, Events) 54 | return root.appCacheNanny 55 | }) 56 | } else if (typeof exports === 'object') { 57 | module.exports = factory(appCache, Events) 58 | } else { 59 | root.appCacheNanny = factory(appCache, Events) 60 | } 61 | })(this, function (applicationCache, Events) { 62 | var DEFAULT_MANIFEST_LOADER_PATH = '/appcache-loader.html' 63 | var DEFAULT_CHECK_INTERVAL = 30000 64 | 65 | var appCacheNanny = new Events() 66 | var nannyOptions = { 67 | loaderPath: DEFAULT_MANIFEST_LOADER_PATH, 68 | checkInterval: DEFAULT_CHECK_INTERVAL, 69 | offlineCheckInterval: DEFAULT_CHECK_INTERVAL 70 | } 71 | 72 | var iframe 73 | var setupDone = false 74 | var setupPending = false 75 | 76 | // 77 | // 78 | // 79 | appCacheNanny.isSupported = function isSupported () { 80 | return !!applicationCache 81 | } 82 | 83 | // 84 | // request the appcache.manifest file and check if there's an update 85 | // 86 | appCacheNanny.update = function update () { 87 | trigger('update') 88 | if (!setupDone) { 89 | setupCallbacks.push(appCacheNanny.update) 90 | if (!setupPending) { 91 | setup() 92 | setupPending = true 93 | } 94 | return true 95 | } 96 | if (!appCacheNanny.isSupported()) { 97 | return false 98 | } 99 | try { 100 | applicationCache.update() 101 | return true 102 | } catch (e) { 103 | // there might still be cases when ApplicationCache is not support 104 | // e.g. in Chrome, when returned HTML is status code 40X, or if 105 | // the applicationCache became obsolete 106 | appCacheNanny.update = noop 107 | return false 108 | } 109 | } 110 | 111 | // 112 | // start auto updating. Optionally pass interval in ms to 113 | // overwrite the current. 114 | // 115 | var intervalPointer 116 | appCacheNanny.start = function start (options) { 117 | if (options) appCacheNanny.set(options) 118 | 119 | if (!setupDone) { 120 | setupCallbacks.push(appCacheNanny.start) 121 | if (!setupPending) { 122 | setup() 123 | setupPending = true 124 | } 125 | return true 126 | } 127 | 128 | clearInterval(intervalPointer) 129 | 130 | // check with offline interval 131 | checkInterval = hasNetworkError ? appCacheNanny.get('offlineCheckInterval') : appCacheNanny.get('checkInterval') 132 | 133 | intervalPointer = setInterval(appCacheNanny.update, checkInterval) 134 | isCheckingForUpdatesFlag = true 135 | trigger('start') 136 | } 137 | 138 | // 139 | // stop auto updating 140 | // 141 | appCacheNanny.stop = function stop () { 142 | if (!isCheckingForUpdatesFlag) return 143 | clearInterval(intervalPointer) 144 | isCheckingForUpdatesFlag = false 145 | trigger('stop') 146 | } 147 | 148 | // 149 | // returns true if the nanny is checking periodically for updates 150 | // 151 | appCacheNanny.isCheckingForUpdates = function isCheckingForUpdates () { 152 | return isCheckingForUpdatesFlag 153 | } 154 | 155 | // 156 | // returns true if an update has been fully received, otherwise false 157 | // 158 | appCacheNanny.hasUpdate = function hasUpdate () { 159 | return hasUpdateFlag 160 | } 161 | 162 | // 163 | // 164 | // 165 | appCacheNanny.set = function setOption (key, value) { 166 | var property, newSettings 167 | if (typeof key === 'object') { 168 | newSettings = key 169 | for (property in newSettings) { 170 | if (newSettings.hasOwnProperty(property)) { 171 | nannyOptions[property] = newSettings[property] 172 | } 173 | } 174 | return 175 | } 176 | nannyOptions[key] = value 177 | } 178 | 179 | // 180 | // 181 | // 182 | appCacheNanny.get = function getOption (key) { 183 | var property 184 | var settings = {} 185 | if (key) { 186 | return nannyOptions[key] 187 | } 188 | 189 | for (property in nannyOptions) { 190 | if (nannyOptions.hasOwnProperty(property)) { 191 | settings[property] = nannyOptions[property] 192 | } 193 | } 194 | return settings 195 | } 196 | 197 | // Private 198 | // ------- 199 | 200 | // this is the internal state of checkInterval. 201 | // It usually differs between online / offline state 202 | var checkInterval = DEFAULT_CHECK_INTERVAL 203 | 204 | // flag if there is a pending update, being applied after next page reload 205 | var hasUpdateFlag = false 206 | 207 | // flag whether the nanny is checking for updates in the background 208 | var isCheckingForUpdatesFlag = false 209 | 210 | // flag if there was an error updating the appCache, usually meaning 211 | // it couldn't connect, a.k.a. you're offline. 212 | var hasNetworkError = false 213 | 214 | // 215 | var isInitialDownload = false 216 | 217 | // 218 | // setup appCacheNanny 219 | // 220 | var noop = function () {} 221 | var APPCACHE_STORE_KEY = '_appcache_nanny' 222 | var setupCallbacks = [] 223 | function setup () { 224 | var scriptTag 225 | 226 | try { 227 | isInitialDownload = !localStorage.getItem(APPCACHE_STORE_KEY) 228 | localStorage.setItem(APPCACHE_STORE_KEY, '1') 229 | } catch (e) {} 230 | 231 | if (!appCacheNanny.isSupported()) { 232 | appCacheNanny.update = noop 233 | return 234 | } 235 | 236 | // https://github.com/gr2m/appcache-nanny/issues/7 237 | if (applicationCache.status !== applicationCache.UNCACHED) { 238 | subscribeToEvents() 239 | setupPending = false 240 | setupDone = true 241 | setupCallbacks.forEach(function (callback) { 242 | callback() 243 | }) 244 | return 245 | } 246 | 247 | // load the appcache-loader.html using an iframe 248 | iframe = document.createElement('iframe') 249 | iframe.src = nannyOptions.loaderPath 250 | iframe.style.display = 'none' 251 | iframe.onload = function () { 252 | // we use the iFrame's applicationCache Object now 253 | applicationCache = iframe.contentWindow.applicationCache 254 | 255 | subscribeToEvents() 256 | setupPending = false 257 | setupDone = true 258 | 259 | // adding a timeout prevented Safari 7.1.4 from throwing 260 | // a InvalidStateError on the first applicationCache.update() call 261 | setTimeout(function () { 262 | setupCallbacks.forEach(function (callback) { 263 | callback() 264 | }) 265 | }, 100) 266 | } 267 | iframe.onerror = function () { 268 | throw new Error('/appcache-loader.html could not be loaded.') 269 | } 270 | 271 | scriptTag = document.getElementsByTagName('script')[0] 272 | scriptTag.parentNode.insertBefore(iframe, scriptTag) 273 | } 274 | 275 | // 276 | // 277 | // 278 | function subscribeToEvents () { 279 | // Fired when the manifest resources have been downloaded. 280 | on('updateready', handleUpdateReady) 281 | 282 | // fired when manifest download request failed 283 | // (no connection or 5xx server response) 284 | on('error', handleNetworkError) 285 | 286 | // fired when manifest download request succeeded 287 | // but server returned 404 / 410 288 | on('obsolete', handleNetworkObsolete) 289 | 290 | // fired when manifest download succeeded 291 | on('noupdate', handleNetworkSuccess) 292 | on('cached', handleNetworkSuccess) 293 | on('progress', handleNetworkSuccess) 294 | on('downloading', handleNetworkSuccess) 295 | 296 | // when browser goes online/offline, look for updates to make sure. 297 | addEventListener('online', appCacheNanny.update, false) 298 | addEventListener('offline', appCacheNanny.update, false) 299 | } 300 | 301 | // 302 | // interface to bind events to cache events 303 | // 304 | function on (eventName, callback) { 305 | applicationCache.addEventListener(eventName, callback, false) 306 | } 307 | 308 | // 309 | // Trigger event on appCacheNanny. Once an update is ready, we 310 | // keep looking for another update, but we stop triggering events. 311 | // 312 | function trigger (eventName, event) { 313 | if (hasUpdateFlag) return 314 | appCacheNanny.trigger(eventName, event) 315 | } 316 | 317 | // 318 | // 319 | // 320 | var pendingUpdateReady = false 321 | function handleUpdateReady () { 322 | // Safari and Firefox (in private mode) can get into an invalid 323 | // applicationCache state, which throws an InvalidStateError error 324 | // on applicationCache.swapCache(). To workaround that, we reset 325 | // everything and set a flag that the next "noupdate" event, that 326 | // will now be triggered when the iframe gets reloadd, is actually 327 | // an "updateready" event. 328 | if (applicationCache.status !== applicationCache.UPDATEREADY) { 329 | pendingUpdateReady = true 330 | reset() 331 | return 332 | } 333 | 334 | if (!hasUpdateFlag) { 335 | hasUpdateFlag = true 336 | // don't use trigger here, otherwise the event wouldn't get triggered 337 | appCacheNanny.trigger('updateready') 338 | } 339 | applicationCache.swapCache() 340 | } 341 | 342 | // 343 | // 344 | // 345 | function handleNetworkSuccess (event) { 346 | var prefix = '' 347 | 348 | // when page gets opened for the very first time, it already has 349 | // the correct assets, but appCache still triggers 'downloading', 350 | // 'progress' and 'cached' events. Once the first 'cached' event 351 | // gets triggered, all assets are cached offline. We prefix these 352 | // initial events with 'init:' 353 | if (isInitialDownload) { 354 | prefix = 'init:' 355 | if (event.type === 'cached') { 356 | isInitialDownload = false 357 | } 358 | } 359 | 360 | // re-trigger event via appCacheNanny 361 | if (pendingUpdateReady) { 362 | trigger('updateready') 363 | pendingUpdateReady = false 364 | } else { 365 | trigger(prefix + event.type, event) 366 | } 367 | 368 | if (!hasNetworkError) return 369 | hasNetworkError = false 370 | 371 | appCacheNanny.start() 372 | trigger('online') 373 | } 374 | 375 | // 376 | // 377 | // 378 | function handleNetworkError (error) { 379 | // re-trigger event via appCacheNanny 380 | trigger('error', error) 381 | 382 | if (hasNetworkError) return 383 | hasNetworkError = true 384 | 385 | // Edge case: private mode in Safari & FF say they support applicationCache, 386 | // but they fail. To get arround that, we only trigger the offline event 387 | // when applicationCache.status != uncached 388 | if (applicationCache.status === applicationCache.UNCACHED) return 389 | 390 | appCacheNanny.start() 391 | 392 | trigger('offline') 393 | } 394 | 395 | // 396 | // The 'obsolete' event gets triggered if the requested *.appcache file 397 | // has been removed or renamed. The intent behind renaming an *.appcache 398 | // file is to clear all locally cached files, it's the only way to do so. 399 | // Therefore we don't treet it as an error, it usually means that there 400 | // is an update availble that becomes visible after the next page reload. 401 | // 402 | function handleNetworkObsolete () { 403 | // re-trigger event via appCacheNanny 404 | trigger('obsolete') 405 | 406 | if (hasNetworkError) { 407 | hasNetworkError = false 408 | trigger('online') 409 | } 410 | 411 | // Once applicationCache status is obsolete, calling .udate() throws 412 | // an error, so we stop checking here 413 | appCacheNanny.stop() 414 | } 415 | 416 | function reset () { 417 | if (iframe) { 418 | iframe.remove() 419 | } 420 | 421 | setupDone = false 422 | setupPending = false 423 | appCacheNanny.update() 424 | } 425 | 426 | return appCacheNanny 427 | }) 428 | -------------------------------------------------------------------------------- /bin/dev-server.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict' 4 | 5 | var fs = require('fs') 6 | var path = require('path') 7 | var util = require('util') 8 | 9 | var Hapi = require('hapi') 10 | var Inert = require('inert') 11 | 12 | var moment = require('moment') 13 | var PORT = 8888 14 | var HOSTNAME = '127.0.0.1' 15 | 16 | var server = new Hapi.Server() 17 | 18 | var version = 1 19 | var timestamp = moment().format('H:mm:ss') 20 | var manifestRemoved = false 21 | 22 | server.connection({ 23 | host: HOSTNAME, 24 | port: PORT 25 | }) 26 | 27 | server.register(Inert, function () {}) 28 | 29 | // Serve dynamic js file to set version / timestamp 30 | server.route({ 31 | method: 'GET', 32 | path: '/version.js', 33 | handler: function (request, reply) { 34 | var setVersion = util.format('document.querySelector("#version").textContent = "%s"', version) 35 | var setLastChange = util.format('document.querySelector("#last-change").textContent = "%s"', timestamp) 36 | 37 | var response = reply([setVersion, setLastChange].join('\n')) 38 | response.type('application/javascript') 39 | } 40 | }) 41 | 42 | // serve appcache-nanny.js 43 | server.route({ 44 | method: 'GET', 45 | path: '/appcache-nanny.js', 46 | handler: function (request, reply) { 47 | reply.file('./appcache-nanny.js') 48 | } 49 | }) 50 | // serve appcache-loader.html 51 | server.route({ 52 | method: 'GET', 53 | path: '/appcache-loader.html', 54 | handler: function (request, reply) { 55 | reply.file('./appcache-loader.html') 56 | } 57 | }) 58 | 59 | // serve manifest.appcache 60 | server.route({ 61 | method: 'GET', 62 | path: '/manifest.appcache', 63 | handler: manifest 64 | }) 65 | 66 | // serve empty favicon 67 | server.route({ 68 | method: 'GET', 69 | path: '/favicon.ico', 70 | handler: function (request, reply) { 71 | reply() 72 | } 73 | }) 74 | 75 | server.route({ 76 | method: 'GET', 77 | path: '/bump-version', 78 | handler: bumpVersion 79 | }) 80 | 81 | server.route({ 82 | method: 'GET', 83 | path: '/remove-manifest', 84 | handler: removeManifest 85 | }) 86 | server.route({ 87 | method: 'GET', 88 | path: '/recreate-manifest', 89 | handler: recreateManifest 90 | }) 91 | 92 | // Serve static assets in public 93 | server.route({ 94 | method: 'GET', 95 | path: '/{param*}', 96 | handler: { 97 | directory: { 98 | path: './demo' 99 | } 100 | } 101 | }) 102 | 103 | function manifest (request, reply) { 104 | var text 105 | 106 | if (manifestRemoved) { 107 | reply().code(404) 108 | return 109 | } 110 | 111 | text = fs.readFileSync(path.join(__dirname, '..', 'demo', 'manifest.appcache')).toString() 112 | text += '\n# last change: ' + timestamp + '\n' 113 | 114 | reply(text).type('text/cache-manifest') 115 | } 116 | 117 | function bumpVersion (request, reply) { 118 | version++ 119 | timestamp = moment().format('H:mm:ss') 120 | reply(version) 121 | } 122 | 123 | function removeManifest (request, reply) { 124 | manifestRemoved = true 125 | reply('manifest removed') 126 | } 127 | function recreateManifest (request, reply) { 128 | manifestRemoved = false 129 | reply('manifest recreated') 130 | } 131 | 132 | if (require.main === module) { 133 | server.start(function () { 134 | console.log('AppCache demo server running at %s\nCTRL + C to shutdown', server.info.uri) 135 | }) 136 | } else { 137 | module.exports = server 138 | } 139 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "appcache-nanny", 3 | "authors": [ 4 | "Gregor Martynus " 5 | ], 6 | "description": "Teaches the applicationCache douchebag some manners!", 7 | "main": "appcache-nanny.js", 8 | "keywords": [ 9 | "appcache", 10 | "Auto Updates for Offline First Applications", 11 | "offline" 12 | ], 13 | "license": "MIT", 14 | "homepage": "http://gr2m.github.io/appcache-nanny", 15 | "ignore": [ 16 | "**/.*", 17 | "node_modules", 18 | "bower_components", 19 | "test", 20 | "tests" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /demo/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gr2m/appcache-nanny/2edfeddc711885d33dc040cf5723081aae07e384/demo/demo.gif -------------------------------------------------------------------------------- /demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | appCache Demo page 6 | 7 | 8 | 9 | 10 | 11 |
12 |

13 | Version
14 | last change: 15 |

16 | 17 | 18 | 19 | 22 | 31 | 32 | 33 | 36 | 48 | 49 | 50 | 53 | 64 | 65 | 66 | 67 | 73 | 74 |
20 | is cached? 21 | 23 |
24 | yes 25 |
26 |
27 | no
28 | 29 |
30 |
34 | has update? 35 | 37 |
38 | yes 39 | (no more events will be triggered)
40 | 41 |
42 |
43 | no
44 | 45 |
46 | 47 |
51 | Is autoupdating? 52 | 54 |
55 | no
56 | 57 | 58 |
59 |
60 | yes
61 | 62 |
63 |
Server 68 |
69 | 70 | 71 |
72 |
75 |
76 | 77 |
78 |

79 | 80 |

81 | 82 | 83 | 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /demo/manifest.appcache: -------------------------------------------------------------------------------- 1 | CACHE MANIFEST 2 | 3 | CACHE: 4 | / 5 | /style.css 6 | /script.js 7 | /appcache-nanny.js 8 | /version.js 9 | 10 | FALLBACK: 11 | / / 12 | -------------------------------------------------------------------------------- /demo/script.js: -------------------------------------------------------------------------------- 1 | /* global appCacheNanny, XMLHttpRequest */ 2 | 3 | // log all appCacheNanny events 4 | [ 5 | 'obsolete', 6 | 'noupdate', 7 | 'downloading', 8 | 'progress', 9 | 'cached', 10 | 'updateready', 11 | 'init:downloading', 12 | 'init:progress', 13 | 'init:cached', 14 | 'start', 15 | 'stop', 16 | 'online', 17 | 'offline' 18 | ].forEach(function (eventName) { 19 | appCacheNanny.on(eventName, function (event) { 20 | log('event', eventName, event) 21 | }) 22 | }) 23 | 24 | // log errors 25 | appCacheNanny.on('error', function () { 26 | log('error', 'appCacheNanny error') 27 | }) 28 | 29 | // update "has update?" state in UI 30 | appCacheNanny.on('updateready', function () { 31 | document.body.setAttribute('data-hasupdate', '1') 32 | }) 33 | 34 | // update "is cached?" state in UI 35 | ;[ 36 | 'noupdate', 37 | 'cached', 38 | 'init:cached' 39 | ].forEach(function (eventName) { 40 | appCacheNanny.on(eventName, function () { 41 | document.body.setAttribute('data-iscached', '1') 42 | }) 43 | }) 44 | appCacheNanny.on('obsolete', function () { 45 | document.body.setAttribute('data-iscached', '0') 46 | }) 47 | // requesting non-existing path will only succeed when 48 | // app is cached, because of the `/ /` line below FALLBACK 49 | request({ 50 | path: '/non-existing', 51 | onSuccess: function () { 52 | document.body.setAttribute('data-iscached', '1') 53 | }, 54 | onError: function (xhr) { 55 | console.log('You can ignore the failing request to /non-existing. It\'s just a test if the app is cached or not.') 56 | 57 | // IE response with error code, but returns the text 58 | if (/appCache Demo page/.test(xhr.responseText)) { 59 | document.body.setAttribute('data-iscached', '1') 60 | } 61 | } 62 | }) 63 | 64 | function log (type, text, event) { 65 | var item = document.createElement('p') 66 | 67 | if (/progress/.test(text)) { 68 | item.innerHTML = '' + type + ' ' + text + ' (' + event.loaded + '/' + event.total + ')' 69 | } else { 70 | item.innerHTML = '' + type + ' ' + text 71 | } 72 | 73 | item.className = type 74 | document.querySelector('#logs').appendChild(item) 75 | document.body.setAttribute('data-haslogs', '1') 76 | } 77 | 78 | function request (options) { 79 | var req = new XMLHttpRequest() 80 | req.open('GET', options.path, true) 81 | 82 | req.onload = function () { 83 | if (req.status !== 200) { 84 | return options.onError && options.onError(req) 85 | } 86 | options.onSuccess && options.onSuccess(req.responseText) 87 | } 88 | 89 | req.onerror = function () { 90 | options.onError && options.onError(req) 91 | } 92 | req.send() 93 | } 94 | 95 | /* eslint-disable no-unused-vars */ 96 | function clearLogs () { 97 | document.querySelector('#logs').innerHTML = '' 98 | document.body.setAttribute('data-haslogs', '0') 99 | } 100 | 101 | function check () { 102 | log('command', 'appCacheNanny.update()') 103 | appCacheNanny.update() 104 | } 105 | function start (interval) { 106 | if (interval) { 107 | log('command', 'appCacheNanny.start({checkInterval: ' + interval + '})') 108 | appCacheNanny.start({checkInterval: interval}) 109 | } else { 110 | log('command', 'appCacheNanny.start()') 111 | appCacheNanny.start() 112 | } 113 | document.body.setAttribute('data-isautoupdating', '1') 114 | } 115 | function stop () { 116 | log('command', 'appCacheNanny.stop()') 117 | appCacheNanny.stop() 118 | document.body.setAttribute('data-isautoupdating', '0') 119 | } 120 | function bumpVersion () { 121 | request({ 122 | path: '/bump-version', 123 | onSuccess: function (version) { 124 | log('server', 'New version: ' + version) 125 | }, 126 | onError: function () { 127 | log('error', 'Could not bump version – server error') 128 | } 129 | }) 130 | } 131 | function removeManifest () { 132 | request({ 133 | path: '/remove-manifest', 134 | onSuccess: function () { 135 | log('server', 'Cache manifes removed.') 136 | appCacheNanny.update() 137 | appCacheNanny.on('obsolete', createManifest) 138 | }, 139 | onError: function () { 140 | log('error', 'Could not remove manifest – server error') 141 | } 142 | }) 143 | } 144 | 145 | function createManifest () { 146 | request({ 147 | path: '/recreate-manifest', 148 | onSuccess: function () { 149 | log('server', 'Cache manifes recreated.') 150 | appCacheNanny.off('obsolete', createManifest) 151 | }, 152 | onError: function () { 153 | log('error', 'Could not recreate manifest – server error') 154 | } 155 | }) 156 | } 157 | -------------------------------------------------------------------------------- /demo/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | font-family: Helvetica, Arial; 3 | background: white; 4 | } 5 | body { 6 | margin: 0; 7 | } 8 | 9 | [data-iscached="0"] .if-iscached, 10 | [data-iscached="1"] .unless-iscached, 11 | [data-hasupdate="0"] .if-hasupdate, 12 | [data-hasupdate="1"] .unless-hasupdate, 13 | [data-isautoupdating="0"] .if-isautoupdating, 14 | [data-isautoupdating="1"] .unless-isautoupdating, 15 | [data-haslogs="0"] .if-haslogs, 16 | [data-haslogs="1"] .unless-haslogs { 17 | display: none; 18 | } 19 | header { 20 | padding: 1em; 21 | background: #eee; 22 | border-bottom: 1px solid #ddd; 23 | } 24 | h1 small { 25 | display: block; 26 | font-weight: normal; 27 | font-size: 0.5em; 28 | } 29 | small { 30 | opacity: .5; 31 | } 32 | table { 33 | width: 100%; 34 | } 35 | th { 36 | text-align: left; 37 | white-space: nowrap; 38 | width: 1px; 39 | padding-right: .5em; 40 | min-width: 130px; 41 | } 42 | td, th { 43 | border-top: 1px solid #000; 44 | vertical-align: top; 45 | padding-top: .5em; 46 | padding-bottom: .5em; 47 | } 48 | button { 49 | border: 0; 50 | padding: 1em; 51 | margin: 0 0 1em; 52 | background: #333; 53 | color: #fff; 54 | border-radius: 4px; 55 | } 56 | 57 | #logs p { 58 | padding: 1em; 59 | margin: 0; 60 | border-bottom: 1px solid #ddd; 61 | } 62 | #logs + p { 63 | padding: 1em; 64 | margin: 0; 65 | } 66 | #logs strong { 67 | font-size: .8em; 68 | font-weight: normal; 69 | border-radius: 4px; 70 | padding: .2em .4em; 71 | color: #fff; 72 | } 73 | #logs .command strong { 74 | background: #333; 75 | } 76 | #logs .event strong { 77 | background: #36F; 78 | } 79 | #logs .error strong { 80 | background: #C00; 81 | } 82 | #logs .server strong { 83 | background: #00B32D; 84 | } 85 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "appcache-nanny", 3 | "description": "Teaches the applicationCache douchebag some manners!", 4 | "main": "appcache-nanny.js", 5 | "scripts": { 6 | "pretest": "standard", 7 | "test": "frontend-test-background mocha test/*.js", 8 | "start": "node ./bin/dev-server.js", 9 | "semantic-release": "semantic-release pre && npm publish && semantic-release post" 10 | }, 11 | "repository": "github:gr2m/appcache-nanny", 12 | "keywords": [ 13 | "browser", 14 | "appcache", 15 | "offlinefirst" 16 | ], 17 | "author": "Gregor Martynus ", 18 | "license": "MIT", 19 | "devDependencies": { 20 | "@gr2m/frontend-test-setup": "^1.2.1", 21 | "chai": "^3.5.0", 22 | "chai-as-promised": "^6.0.0", 23 | "colors": "^1.1.2", 24 | "hapi": "^15.0.1", 25 | "inert": "^4.0.0", 26 | "mocha": "^3.0.0", 27 | "moment": "^2.14.1", 28 | "semantic-release": "^6.3.0", 29 | "standard": "^8.0.0" 30 | }, 31 | "standard": { 32 | "ignore": [ 33 | "bower_components" 34 | ] 35 | }, 36 | "frontend-test-setup": { 37 | "server": { 38 | "cmd": "node ./bin/dev-server.js", 39 | "host": "127.0.0.1", 40 | "port": 8888 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | /* global describe, beforeEach, it */ 2 | 3 | require('@gr2m/frontend-test-setup') 4 | 5 | function toValue (result) { 6 | if (isError(result.value)) { 7 | var error = new Error(result.value.message) 8 | Object.keys(result.value).forEach(function (key) { 9 | error[key] = result.value[key] 10 | }) 11 | throw error 12 | } 13 | 14 | return result.value 15 | } 16 | 17 | function isError (value) { 18 | return value && value.name && /error/i.test(value.name) 19 | } 20 | 21 | describe('hoodie.account', function () { 22 | this.timeout(30000) 23 | 24 | beforeEach(function () { 25 | return this.client.url('/') 26 | }) 27 | 28 | it('should be funky', function () { 29 | return this.client 30 | 31 | // version is loaded from server set with JavaScript asynchronously 32 | .getText('#version') 33 | .should.eventually.equal('1') 34 | // cache button should be visible, as app is not cached initially 35 | .isVisible('#btn-cache') 36 | .should.eventually.equal(true) 37 | // when clicked on cache button, "cached" event should eventually appear 38 | .click('#btn-cache') 39 | 40 | .waitUntil(function () { 41 | return this.execute(function () { 42 | var $logs = document.querySelector('#logs') 43 | if (!$logs) return 44 | return ($logs.textContent || '').indexOf('cached') >= 0 45 | }).then(toValue) 46 | }, 10 * 1000, 1000) 47 | .getText('#logs') 48 | .should.eventually.match(/cached/) 49 | 50 | // non-existing paths should no load due to the appCache FALLBACK: / / 51 | .url('/appcache-fallback-test') 52 | 53 | .getText('#version') 54 | .should.become('1') 55 | 56 | // Is cached? should become "yes" 57 | .waitUntil(function () { 58 | return this.execute(function () { 59 | return document.body.dataset.iscached === '1' 60 | }).then(toValue) 61 | }, 10 * 1000) 62 | 63 | // check for update 64 | .click('#btn-check') 65 | 66 | // wait until first "noupdate" is visible 67 | .waitUntil(function () { 68 | return this.execute(function () { 69 | return document.querySelector('#logs').textContent.search(/noupdate/) >= 0 70 | }).then(toValue) 71 | }, 10 * 1000) 72 | }) 73 | }) 74 | --------------------------------------------------------------------------------