#248 Offline Apps Part 2
Learn how to make a site usable offline with HTML 5 localStorage. This last part of the series covers jquery-tmpl and jquery-offline.
- Download:
- source codeProject Files in Zip (120 KB)
- mp4Full Size H.264 Video (27.6 MB)
- m4vSmaller H.264 Video (17.1 MB)
- webmFull Size VP8 Video (43.9 MB)
- ogvFull Size Theora Video (36.1 MB)
Resources
bash
curl https://github.com/jquery/jquery-tmpl/raw/master/jquery.tmpl.js > public/javascripts/jquery.tmpl.js curl https://github.com/wycats/jquery-offline/raw/master/lib/jquery.offline.js > public/javascripts/jquery.offline.js curl https://github.com/wycats/jquery-offline/raw/master/lib/json.js > public/javascripts/json.js
items_controller.rb
respond_to :html, :json def index @items = Item.all respond_with(@items) end
layouts/application.html.erb
<%= javascript_include_tag :defaults, "jquery.tmpl", "json", "jquery.offline" %>
items/index.html.erb
<script type="text/html" id="item_template"> <li>${item.name}</li> </script> <ol id="items"> <li><em>Loading items...</em></li> </ol>
application.js
$(function() { if ($.support.localStorage) { $(window.applicationCache).bind("error", function() { console.log("There was an error when loading the cache manifest."); }); if (!localStorage["pendingItems"]) { localStorage["pendingItems"] = JSON.stringify([]); } $.retrieveJSON("/items.json", function(data) { var pendingItems = $.parseJSON(localStorage["pendingItems"]); $("#items").html($("#item_template").tmpl(data.concat(pendingItems))); }); $("#new_item").submit(function(e) { var pendingItems = $.parseJSON(localStorage["pendingItems"]); var item = {[data]($(this).serialize(),) [item]({"name":$("#item_name").val()}};) $("#item_template").tmpl(item).appendTo("#items"); pendingItems.push(item); localStorage["pendingItems"] = JSON.stringify(pendingItems) $("#item_name").val(""); sendPending(); e.preventDefault(); }); function sendPending() { if (window.navigator.onLine) { var pendingItems = $.parseJSON(localStorage["pendingItems"]); if (pendingItems.length > 0) { var item = pendingItems[0]; $.post("/items", item.data, function(data) { var pendingItems = $.parseJSON(localStorage["pendingItems"]); pendingItems.shift(); localStorage["pendingItems"] = JSON.stringify(pendingItems) setTimeout(sendPending, 100); }); } } } sendPending(); $(window).bind("online", sendPending); } else { alert("Try a different browser."); } });