Offline Application Cache

Post on 29-Jan-2018

3,595 views 0 download

transcript

Offline Application CacheJonathan Stark

1

What is AppCache?

2

The Basics

3

Manifest File

• A simple text document

• Hosted on your web server

• Contains a list of static resources

4

demo.manifest

CACHE MANIFEST

index.html

logo.jpg

scripts/demo.js

styles/screen.css

5

index.html

<html manifest="demo.manifest">

6

.htaccess

AddType text/cache-manifest .manifest

7

It Works!

• User loads index.html normally

• Listed files download in the background

• User can now go offline

8

What About Updates?

• Update your content (HTML, CSS, JS, IMG)

• Update your manifest

• All files re-download next time

9

Online Whitelist

10

demo.manifest

CACHE MANIFEST

index.html

scripts/demo.js

styles/screen.css

NETWORK:

logo.jpg

11

Offline Fallbacks

12

demo.manifest

CACHE MANIFEST

index.html

scripts/demo.js

styles/screen.css

FALLBACK:

logo.jpg offline.jpg

13

demo.manifest

CACHE MANIFEST

index.html

scripts/demo.js

styles/screen.css

FALLBACK:

images/ images/offline.jpg

14

Dynamic Manifest

15

manifest.php<?phpecho "CACHE MANIFEST\n";$dir = new RecursiveDirectoryIterator(".");foreach(new RecursiveIteratorIterator($dir) as $file) { if ($file->IsFile() and $file != "./manifest.php" and substr($file->getFilename(), 0, 1) != ".") { echo $file . "\n"; }}

16

Debugging

17

access_log

tail -f /var/log/apache2/access_log

18

JavaScript API// Convenience array of status valuesvar cacheStatusValues = [];cacheStatusValues[0] = 'uncached';cacheStatusValues[1] = 'idle';cacheStatusValues[2] = 'checking';cacheStatusValues[3] = 'downloading';cacheStatusValues[4] = 'updateready';cacheStatusValues[5] = 'obsolete';

19

JavaScript API// Listeners for all possible eventsvar cache = window.applicationCache;cache.addEventListener('cached', logEvent, false);cache.addEventListener('checking', logEvent, false);cache.addEventListener('downloading', logEvent, false);cache.addEventListener('error', logEvent, false);cache.addEventListener('noupdate', logEvent, false);cache.addEventListener('obsolete', logEvent, false);cache.addEventListener('progress', logEvent, false);cache.addEventListener('updateready', logEvent, false);

20

JavaScript API// Log every event to the consolefunction logEvent(e) { var online, status, type, message; online = (navigator.onLine) ? 'yes' : 'no'; status = cacheStatusValues[cache.status]; type = e.type; message = 'online: ' + online; message+= ', event: ' + type; message+= ', status: ' + status; if (type == 'error' && navigator.onLine) { message+= ' (prolly a syntax error in manifest)'; } console.log(message);}

21

JavaScript API// Check for manifest changes every 10 secondssetInterval(function(){cache.update()}, 10000);

22

Demo!

23

More Info

• http://jonathanstark.com/books

• http://jonathanstark.com/contact

• http://jonathanstark.com/e4h

24