Featured

JQuery Mobile App: Caching Pages in local Storage Seamlessly

English: jQuery Mobile logo.

jQuery Mobile. (Photo credit: Wikipedia)

While JQuery Mobile provides a way to cache and prefetch pages and store them in DOM, it does not provide a seamless mechanism to persist these pages in local storage. Local Storage a mechanism introduced in HTML5 to store data locally in the browser and remains persisted between browser sessions.

The mechanism below has been tested with Jquery Mobile 1.2 . The process works as below:

  1. Intercept “pagebeforechange” event to find out if the page is already in DOM or cache.
    1. If not in DOM or Cache – do nothing- continue as usual
    2. If in cache but not in DOM, put the data in DOM so that the loadPage automatically finds it.
  2. Now Intercept “pageload” event to populate the localStorage cache.
    1. The example only cache the pages (pages with data-role=”page”) and with attribute “data-local-storage=true

Here’s the code:

$(document).bind( "pagebeforechange", function( e, data ) {

	if ( typeof data.toPage === "string" ) {
		var pageId = getPageId(data.toPage);

		if(localStorage.getItem(pageId) == null) {

		} else {
			if($("#" + pageId) == null || $("#" + pageId).length == 0) {
				var html =  localStorage.getItem(pageId);
				var all = $( "<div></div>" );
				all.get( 0 ).innerHTML = html;
				page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first();
				var u = data.toPage;
				if($.mobile.path.isAbsoluteUrl(u)) {
					u = u.substring($.mobile.path.parseUrl(u).domain.length);
				}
				page.attr("data-url", u);
				$('body').append(page);
			}
		}
	}
});		

		$( document ).bind( "pageload", function( event, data ){

			console.log(data.xhr.responseText);

			var pageId = getPageId(data.dataUrl);

			if(data.xhr.responseText != null) {
				var all = $( "<div></div>" );
				all.get( 0 ).innerHTML = data.xhr.responseText;
				var page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first();

				if(page.jqmData("local-cache") === true) {
					localStorage.setItem(pageId, data.xhr.responseText);
				}
			}

		});

Enhanced by Zemanta

Also published on Medium.

Discussion

No comments for “JQuery Mobile App: Caching Pages in local Storage Seamlessly”