Showing posts with label offline. Show all posts
Showing posts with label offline. Show all posts

Monday 23 February 2015

Basic HTML5 web app template which works online and offline

Here I provide the code for 3 main files in the creation of a web app. This obviously remains working when there is no internet connection, but differently since back end databases etc. would no longer be available.
In order for this to work, you should also download jQuery.
First we will need an appcache file (in this case mobile.appcache) which tells the browser what to store locally. It should look like this:
CACHE MANIFEST
# 2015-02-23 v1.0.0
index.html
html5shiv/3.7.2/html5shiv.min.js
respond/1.4.2/respond.min.js
jquery/1.11.2/jquery.min.js
onlineoffline.plugin.js

NETWORK:
*
Every time you make a change, update the date and version numbers in order for receivers of the web app to get the updated version.
Next we'll need a jQuery plugin (onlineoffline.plugin.js) to handle differences in web app behaviour when online or offline:
(function($)
{
    $.fn.extend(
    {
        onlineoffline:function(options)
        {
            
        }
    });

    $.fn.handleOnline = function()
    {
        console.log('Handling online');
    };

    $.fn.handleOffline = function()
    {
        console.log('Handling offline');
    };
})(jQuery);
Finally, the HTML file (index.html). This makes a reference to the appcache and detects if the web app is online or offline. I've kept the CSS in this file too in order to reduce the number of files needed in this example.
<!DOCTYPE html>
<html lang="en" manifest="mobile.appcache">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <title>Simple online/offline</title>
    <style>
    body
    {
      font:0.9em/1.5em Sans-serif;
    }
    </style>
  </head>
  <body>
    <h1>Hello world!</h1>
    <script src="jquery/1.11.2/jquery.min.js"></script>    
    <script src="onlineoffline.plugin.js"></script>
    <script>
    setInterval(function()
    {
      if(navigator.onLine == true)
      {
        $(this).handleOnline();
      }
      else
      {
        $(this).handleOffline();
      }      
    }, 250);
    </script>
  </body>
</html>