[HTML5][Storage] オフライン閲覧
HTML5のStorageとJQuery Mobileを用いてオフライン閲覧のサンプルを作りました。
- jquery mobileはコンテンツがページ単位ですので、ページをHTML5のStorageで保存しています。
- anchor要素をクリックした時、Storageにページがあれば、$.mobile.changePageを実行します。もし、Storageにページがなければネットワークからコンテンツを取得します。
<!DOCTYPE html> <html> <head> <meta http-equiv="content-language" content="ja"> <meta charset="UTF-8"> <title>コンテンツをHTML5ストレージでキャッシュする</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" /> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> <script type="text/javascript"> var storage = sessionStorage; <!-- セッションストレージ --> var url= 'test.html'; function preload() { console.log('preload contents'); $.get(url, function(data) { console.log('test.html get.'); var content; var $doc = $(data); content = $doc.filter('#top'); var preload = '<div id="preload" data-role="page">' + content.html() + '</div>'; storage.setItem(url, preload); //console.log('#preaload:' + preload); }); } $(document).ready(function() { preload(); $("a").on('click', function() { var href = $(this).attr('href'); console.log('click1. href:' + href); var page; if ((page = storage.getItem(href))) { // storageにコンテンツがあれはそれを使う。 console.log(href + ' load from storage'); $('#preload').replaceWith(page); $.mobile.changePage('#preload'); return false; } else { console.log(href + ' load from network'); $.mobile.changePage(href); } }); }); </script> </head> <body> <div data-role="page"> <div data-role="header"> <h2>オフライン閲覧例</h2> </div> <div data-role="content"> <p>jQuery MobileのコンテンツをHTML5のStorageで保存してオフライン閲覧できる>ようにしたサンプル。</p> <ul> <li>anchorタグのhref属性のURLを事前にajaxでロード</li> <li>ロードしたページをHTML5のセッションストレージで保存する。</li> <li>セッションが有効な間は、test.htmlリンクをクリックすると、セッションス トレージからコンテンツをロードする。</li> </ul> <p><a href="test.html">test.html は、HTMLT5のストレージからロード</a></p> <p><a href="test2.html">test2.htmlは、ネットワーク経由でロード</a></p> </div> <div data-role="footer"> <h4>Copyright 2013</h4> </div> </div> <!-- id=preloadのコンテンツをreplaceWithで置き換える。--> <div id="preload" data-role="page"> </div> </body> </html>
test1.htmlファイル
<!DOCTYPE html> <html> <head> <meta http-equiv="content-language" content="ja"> <meta charset="UTF-8"> <title>test</title> </head> <body> <div id="top" data-role="page"> <div data-role="header"> <h2>test.html</h2> </div> <div data-role="content"> <p>こんばんは。</p> </div> <div data-role="footer"> <h4>Copyright 2013</h4> </div> </div> </body> </html>