• Stars
    star
    670
  • Rank 64,762 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 14 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Rack and Rails plugin for building offline web applications

HTML5 Offline

HTML5 provides two robust offline capabilities already implemented in popular mobile devices, such as the iPhone and Android, and on modern desktop browsers based on the Webkit and Gecko rendering engines.

Usage

The easiest way to use Rack::Offline is by using Rails::Offline in a Rails application.
In your router:

match "/application.manifest" => Rails::Offline

This will automatically cache all JavaScript, CSS, and HTML in your public
directory, and will cause the cache to be updated each request in development
mode.

You can fine-tune the behavior of Rack::Offline by using it directly:

offline = Rack::Offline.configure do
  cache "images/masthead.png"

  public_path = Rails.public_path
  Dir[public_path.join("javascripts/*.js")].each do |file|
    cache file.relative_path_from(public_path)
  end

  network "/"
end

And when used with Rails asset pipeline:

  if Rails.env.production?
    offline = Rack::Offline.configure :cache_interval => 120 do      
      cache ActionController::Base.helpers.asset_path("application.css")
      cache ActionController::Base.helpers.asset_path("application.js")
      # cache other assets
      network "/"  
    end
    match "/application.manifest" => offline  
  end

You can pass an options Hash into #configure in Rack::Offline:

name purpose value in Rails::Offline
:cache false means that the browser should download the assets on each request if a connection to the server can be made the same as config.cache_classes
:logger a logger to send messages to Rails.logger
:root The location of files listed in the manifest Rails.public_path

Application Cache

The App Cache allows you to specify that the browser should cache certain files, and ensure that the user can access them even if the device is offline.

You specify an application’s cache with a new manifest attribute on the html element, which must point at a location on the web that serves the manifest. A manifest looks something like this:

CACHE MANIFEST

javascripts/application.js
javascripts/jquery.js
images/masthead.png

NETWORK:
/

This specifies that the browser should cache the three files immediately following CACHE MANIFEST, and require a network connection for all other URLs.

Unlike HTTP caches, the browser treats the files listed in the manifest as an atomic unit: either it can serve all of them out of the manifest or it needs to update all of them. It will not flush the cache unless the user specifically asks the browser to clear the cache or for security reasons.

Additionally, the HTML file that supplies the manifest attribute is implicitly in the manifest. This means that the browser can load the HTML file and all its cached assets as a unit, even if the device is offline.

In short, the App Cache is a much stickier, atomic cache. After storing an App Cache, the browser takes the following (simplified) steps in subsequent requests:

  1. Immediately serve the HTML file and its assets from the App Cache. This happens
    whether or not the device is online
  2. If the device is offline, treat any resources not specified in the App Cache
    as 404s. This means that images will appear broken, for instance, unless you
    make sure to include them in the App Cache.
  3. Asynchronously try to download the file specified in the manifest attribute
  4. If it successfully downloads the file, compare the manifest byte-for-byte with
    the stored manifest.
    • If it is identical, do nothing.
    • If it is not identical, download (again, asynchronously), all assets specified
      in the manifest
  5. Along the way, fire a number of JavaScript events. For instance, if the browser
    updates the cache, fire an updateready event. You can use this event to
    display a notice to the user that the version of the HTML they are using is
    out of date

App Cache Considerations

The first browser hit after you change the HTML will always serve up stale HTML
and JavaScript. You can mitigate this in two obvious ways:

  1. Treat your mobile web app as an API consumer and make sure that your app
    can support a “client” that’s one version older than the current version
    of the API.
  2. Force the user to reload the HTML to see newer data. You can detect this
    situation by listening for the updateready event

A good recommendation is to have your server support clients at most one
version old, but force older clients to reload the page to get newer data.

Regular users of your application will receive updates through normal usage,
and will never be forced to update. Irregular users may be forced to update
if they pick up the application months after they last used in. In all, a
pretty good trade-off.

While this may seem cumbersome at first, it makes it possible for your users
to browse around your application more naturally when they have flaky
connections, because the process of updating assets (including HTML)
always happens in the background.

Updating the App Cache

You will need to make sure that you update the cache manifest when any of
the underlying assets change.

Rack::Offline handles this using two strategies:

  1. In development, it generates a SHA hash based on the timestamp for each
    request. This means that the browser will always interpret the cache
    manifest as stale. Note that, as discussed in the previous section,
    you will need to reload the page twice to get updated assets.
  2. In production, it generates a SHA hash once based on the contents of
    all the assets in the manifest. This means that the cache manifest will
    not be considered stale unless the underlying assets change.

Rails::Offline caches all JavaScript, CSS, images and HTML
files in public and uses config.cache_classes to determine which of
the above modes to use. In Rails, you can get more fine-grained control
over the process by using Rack::Offline directly.

Local Storage

Browsers that support the App Cache also support Local Storage, from the
HTML5 Web Storage Spec. IE8 and above also support Local
Storage.

Local Storage is a JavaScript API to an extremely simple key-value store.

It works the same as accessing an Object in JavaScript, but persists the
value across sessions.

localStorage.title = "Welcome!"
localStorage.title //=> "Welcome!"

delete localStorage.title
localStorage.title //=> undefined

Browsers can offer different amounts of storage using this API. The
iPhone, for instance, offers 5MB of storage, after which it asks the
user for permission to store an additional 10MB.

You can reclaim storage from a key by deleteing it or
by overwriting its value. You can also enumerate over all keys in
the localStorage using the normal JavaScript for/in
API.

In combination with the App Cache, you can use Local Storge to store
data on the device, making it possible to show stale data to your
users even if no connection is available (or in flaky connection
scenarios).

Basic JavaScript Strategy

You can implement a simple offline application using only a few
lines of JavaScript. For simplicity, I will use jQuery, but you
can easily implement this in pure JavaScript as well. The
example is heavily commented, but the total number of lines of
actual JavaScript is quite small.

jQuery(function($) {
  // Declare a function that can take a JS object and
  // populate our HTML. Because we used the App Cache
  // the HTML will be present regardless of online status
  var updateArticles = function(object) {
    template = $("#articles")
    localStorage.articles = JSON.stringify(object);
    $("#article-list").html(template.render(object));
  }

  // Create a flag so we don't poll the server twice
  // at once
  var updating = false;

  // Create a function that will ask the server for
  // updates to the article list
  var remoteUpdate = function() {
    // Don't ping the server again if we're in the
    // process of updating
    if(updating) return;

    updating = true;

    $("#loading").show();
    $.getJSON("/article_list.json", function(json) {
      updateArticles(json);
      $("#loading").hide();
      updating = false;
    });
  }

  // If we have "articles" in the localStorage object,
  // update the HTML with the stale articles. Even if
  // the user never gets online, they will at least
  // see the stale content
  if(localStorage.articles) updateArticles(JSON.parse(localStorage.articles));

  // If the user was offline, and goes online, ask
  // the server for updates
  $(window).bind("online", remoteUpdate);

  // If the user is online, ask for updates now
  if(window.navigator.onLine) remoteUpdate();
})

More Repositories

1

javascript-decorators

2,397
star
2

jquery-offline

A jQuery plugin to facilitate conveniently working with local storage
JavaScript
836
star
3

moneta

a unified interface to key/value stores
Ruby
476
star
4

merb-core

Merb Core: All you need. None you don't.
Ruby
437
star
5

bundler

Ruby
409
star
6

merb

master merb branch
Ruby
339
star
7

starbeam-historical

TypeScript
269
star
8

artifice

Replaces Net::HTTP with a subclass that routes all requests to a Rack application
Ruby
216
star
9

merb-plugins

Merb Plugins: Even more modules to hook up your Merb installation
JavaScript
209
star
10

merb-more

Merb More: The Full Stack. Take what you need; leave what you don't.
187
star
11

minispade

JavaScript
175
star
12

textmate

Command-line package manager for textmate
Ruby
159
star
13

rust-activesupport

Small demos that illustrate Rust's expressiveness
Rust
132
star
14

rake-pipeline-web-filters

Ruby
116
star
15

newgem-template

A basic template for building a brand new gem
Ruby
106
star
16

guides

Build your own Rails guides
JavaScript
92
star
17

javascript-private-state

A proposal for private state in JavaScript (Stage 0)
92
star
18

jspec

A JavaScript BDD Testing Library
JavaScript
83
star
19

dbmonster

A demo of dbmon running on the idempotent-rerender branches of Ember and HTMLBars
JavaScript
62
star
20

mio-book

62
star
21

handlebars-site

HTML
55
star
22

net-http

Ruby
43
star
23

rust-civet

A Rust web server
Rust
43
star
24

js_module_transpiler

JS Module Transpiler is an experimental compiler that allows you to write your JavaScript using a subset of the current ES6 module syntax, and compile it into AMD modules (and soon, CommonJS modules)
Ruby
42
star
25

osx-window-sizing

AppleScripts to resize windows simply
42
star
26

irb2

Ruby
37
star
27

hammer.rs

An option parsing library that deserializes flags into structs
Rust
37
star
28

asdf

Make the current directory available on port 9292
Ruby
35
star
29

parsejs

JavaScript
34
star
30

railsnatra

Ruby
32
star
31

benchwarmer

Prettier Benchmarking for Ruby
Ruby
32
star
32

muse

A library that can create HTML or PDF books from an extended Markdown format
Ruby
29
star
33

rust-bridge

Ruby
27
star
34

rust-arel

An in-progress port of the Ruby SQL building library arel
Rust
25
star
35

vigilo

A lightweight, simple API for watching the file system
Ruby
25
star
36

rails_assets

temporary home of Rails 3.1 assets until it's moved into master (in short order)
Ruby
24
star
37

dm-adapters

DataMapper Adapters
Ruby
22
star
38

ember-next-experiments

Shell
19
star
39

merb-extlib

Ruby core extensions library extracted from Merb core.
Ruby
19
star
40

experimental-amber-todos

The SproutCore todos tutorial using the single-file alpha Amber distribution
JavaScript
18
star
41

looper

Static analysis tools for ES6
JavaScript
16
star
42

rufo

a Ruby bridge to flying saucer
Ruby
16
star
43

ruby-spidermonkey

A Ruby Binding to Spidermonkey
C
15
star
44

shimmer

An experimental attempt to restructure Glimmer's concepts around a smaller set of primitives.
TypeScript
15
star
45

jquery-governance

Ruby
15
star
46

argon

Rust
13
star
47

language-reporting

Rust
13
star
48

chainable_compare

Ruby
12
star
49

net2-reactor

Ruby
12
star
50

hbs-parser-next

Messing around with a combinator-based approach to parser while stuck at home
TypeScript
12
star
51

github-issues-demo

The code for the Github Issues demo I presented at EmberCamp UK
CSS
11
star
52

prometheus

11
star
53

everafter

An experiment with making the Glimmer reactivity system more general
TypeScript
11
star
54

alexandria

Ruby bindings to the Google Data API
Ruby
11
star
55

rails-simple-benches

Some Rails benches that work across Rails versions and can be used to compare perf progress
Ruby
10
star
56

html5-parser

JavaScript
10
star
57

Unix.rb

C
10
star
58

sparta

Javascript running on Rubinius VM
Ruby
10
star
59

polaris-sketchwork

A collection of proposals that I (@wycats) am working on fleshing out for inclusion in Polaris.
JavaScript
10
star
60

rails-extension-tutorial

Ruby
9
star
61

rails-benches

Application benchmarks to confirm that optimization impact real-world performance
9
star
62

merb_dm_rest

A HTTP DataMapper bridge served via Merb
Ruby
9
star
63

syntax-highlighter

A web syntax highlighter to make it easy to write code to be pasted into keynote
JavaScript
9
star
64

nnhistory

HTML
9
star
65

rails2_on_rails3

Ruby
9
star
66

abbot-from-scratch

Ruby
9
star
67

jetty-rb

Ruby
9
star
68

allocation_counter

Ruby
8
star
69

proc-macro-workshop

Rust
8
star
70

active_params

8
star
71

software-patent-petition

8
star
72

w3c-dom

A W3C-compliant DOM written on top of libxml2 (very early stages)
Ruby
8
star
73

sproutcore-chrome-extension

A Chrome DevTools extension for SproutCore
JavaScript
8
star
74

jsmodules

CSS
8
star
75

indexeddb-experiment

This is an experiment building an IndexedDB adapter for Ember. It is very experimental and is tracking changes we are making in ember-data, so it is also unstable.
JavaScript
8
star
76

ember-future

Some experiments
JavaScript
7
star
77

rails-api

Ruby
7
star
78

cargo-website

CSS
7
star
79

jquery-ui-sproutcore20

JavaScript
7
star
80

modularity_olympics

My entry to Nick Kallen's modularity olympics (using the Middleware pattern as seen in Rack)
Ruby
7
star
81

simple-callbacks-refactor

Quick demo of how to make callbacks faster
Ruby
7
star
82

joy-ide

An IDE inspired by Rich Kilmer's Talk at Gogaruco
6
star
83

routed-http.rs

Combining rust-http with route-recognizer.rs to create routable HTTP
Rust
6
star
84

rake-pipeline-rails

Ruby
6
star
85

slicehub

An application for managing slices
6
star
86

wand

Rust
5
star
87

merb-docs

Ruby
5
star
88

core-storage

TypeScript
5
star
89

railsconf-rust-demo

Rust
5
star
90

sproutcore-interactive-tutorials

JavaScript
5
star
91

js_tabs_example

An example (not production code!) of how to write evented JS using tabs as an example
JavaScript
5
star
92

rdoc

rdoc fork to support arbitrary API level filtering
5
star
93

laszlo_post_api

Laszlo POST-API
Java
5
star
94

rust-experiments

Rust
5
star
95

rubygems-bug-demo

Ruby
5
star
96

handlebars-parser

An experimental rewrite of the Handlebars parser using Jison
JavaScript
5
star
97

at-media

The code from my @media talk
4
star
98

gkc

Rust
4
star
99

stalkr

Ruby
4
star
100

css_to_xpath

Extracted from Nokogiri in anticipation of merging into Merb
Ruby
4
star