I want to develop a webapp to manage sports competitions. It must be able to run completely offline, store data locally and post the results online via AJAX whenever there is an internet connection available - this may be the day after.
How to store data using Javascript?
The simplest one is Web Storage - a key-value string storage, allowing Web applications to store data either persistently and cross-window ( localStorage ) or for a single session in a single browser tab ( sessionStorage ).
If the user has installed an icon for the PWA in the operating system, the browser may grant persistent storage.
For PWAs, you could cache the static files composing your application shell (JS/CSS/HTML files) in the Cache API and fill in the offline page data from IndexedDB. There are no hard and fast rules around this however.
Progressive Web Apps (PWAs) are web applications that use modern technologies to provide a user experience that closely mimics a native app. PWAs have become very popular in recent years as they do not only improve performance and user experience but are also accessible when a user is offline.
If you are supporting modern browsers, you can make use of HTML5 Local Storage.
Persistent local storage is one of the areas where native client applications have held an advantage over web applications. For native applications, the operating system typically provides an abstraction layer for storing and retrieving application-specific data like preferences or runtime state. These values may be stored in the registry, INI files, XML files, or some other place according to platform convention. If your native client application needs local storage beyond key/value pairs, you can embed your own database, invent your own file format, or any number of other solutions.
Example
// Save data to a the current session's store
sessionStorage.setItem("username", "John");
// Access some stored data
alert( "username = " + sessionStorage.getItem("username"));
// Get the text field that we're going to track
var field = document.getElementById("field");
// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if ( sessionStorage.getItem("autosave")) {
// Restore the contents of the text field
field.value = sessionStorage.getItem("autosave");
}
// Check the contents of the text field every second
setInterval(function(){
// And save the results into the session storage object
sessionStorage.setItem("autosave", field.value);
}, 1000);
Browser Compatibility
Older Browsers
Use Polyfill.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With