Web Tutorial 2

Payza Signup
 

HTML5 Application Cache | What is Application Cache? | HTML5 Cache Manifest Example | Cache Manifest Basics | The Manifest File | Updating the Cache



HTML5 Application Cache

With HTML5 it is easy to make an offline version of a web application, by creating a cache manifest file.

What is Application Cache?

HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.
Application cache gives an application three advantages:

  1. Offline browsing - users can use the application when they're offline 
  2. Speed - cached resources load faster 
  3. Reduced server load - the browser will only download updated/changed resources from the server

Browser Support

Application cache is supported in all major browsers, except Internet Explorer.

HTML5 Cache Manifest Example

The example below shows an HTML document with a cache manifest (for offline browsing):
 <html manifest="demo.appcache">

<body>
The content of the document......
</body>

</html>

Cache Manifest Basics

To enable application cache, include the manifest attribute in the document's <html>  tag:

<html manifest="demo.appcache">
...
</html>

Every page with the manifest attribute specified will be cached when the user visits it. If the manifest attribute is not specified, the page will not be cached (unless the page is specified directly in the manifest file).
The recommended file extension for manifest files is: ".appcache" A manifest file needs to be served with the correct MIME-type, which is "text/cache-manifest". Must be configured on the web server.

The Manifest File

The manifest file is a simple text file, which tells the browser what to cache (and what to never cache). The manifest file has three sections:
  • CACHE MANIFEST - Files listed under this header will be cached after they are downloaded for the first time
  • NETWORK - Files listed under this header require a connection to the server, and will never be cached
  • FALLBACK - Files listed under this header specifies fallback pages if a page is inaccessible

CACHE MANIFEST The first line, CACHE MANIFEST, is required:
CACHE MANIFEST
/theme.css
/logo.gif
/main.js

The manifest file above lists three resources: a CSS file, a GIF image, and a JavaScript file. When the manifest file is loaded, the browser will download the three files from the root directory of the web site. Then, whenever the user is not connected to the internet, the resources will still be available.
NETWORK The NETWORK section below specifies that the file "login.asp" should never be cached, and will not be available offline:
NETWORK:
login.asp 

An asterisk can be used to indicate that all other resources/files require an internet connection:
NETWORK:
*
FALLBACK
The FALLBACK section below specifies that "offline.html" will be served in place of all files in the /html/ catalog, in case an internet connection cannot be established:
FALLBACK:
/html/ /offline.html
Note: The first URI is the resource, the second is the fallback.

Updating the Cache

Once an application is cached, it remains cached until one of the following happens:
  • The user clears the browser's cache
  • The manifest file is modified (see tip below)
  • The application cache is programmatically updated
  • Example - Complete Cache Manifest File
CACHE MANIFEST
# 2012-02-21 v1.0.0
/theme.css
/logo.gif
/main.js

NETWORK:
login.asp

FALLBACK:
/html/ /offline.html
Tip: Lines starting with a "#" are comment lines, but can also serve another purpose. An application's cache is only updated when its manifest file changes. If you edit an image or change a JavaScript function, those changes will not be re-cached. Updating the date and version in a comment line is one way to make the browser re-cache your files.

Notes on Application Cache

Be careful with what you cache.
Once a file is cached, the browser will continue to show the cached version, even if you change the file on the server. To ensure the browser updates the cache, you need to change the manifest file.
Note: Browsers may have different size limits for cached data (some browsers have a 5MB limit per site).

[Read More...]


HTML5 Web Storage - What is HTML5 Web Storage? - localStorage and sessionStorage - localStorage Object - sessionStorage Object



HTML5 web storage, a better local storage than cookies.

What is HTML5 Web Storage?

With HTML5, web pages can store data locally within the user's browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance.
The data is stored in key/value pairs, and a web page can only access data stored by itself.

Browser Support

Web storage is supported in Internet Explorer 8+, Firefox, Opera, Chrome, and Safari.
Note: Internet Explorer 7 and earlier versions, do not support web storage.

localStorage and sessionStorage 

There are two new objects for storing data on the client:
  • localStorage - stores data with no expiration date
  • sessionStorage - stores data for one session
Before using web storage, check browser support for localStorage and sessionStorage:

if(typeof(Storage)!=="undefined")
  {
  // Yes! localStorage and sessionStorage support!
  // Some code.....
  }
else
  {
  // Sorry! No web storage support..
  }

The localStorage Object

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
Example:
localStorage.lastname="Smith";
document.getElementById("result").innerHTML="Last name: "
+ localStorage.lastname;

Example explained:
  • Create a localStorage key/value pair with key="lastname" and value="Smith"
  • Retrieve the value of the "lastname" key and insert it into the element with id="result"
Tip: Key/value pairs are always stored as strings. Remember to convert them to another format when needed.
The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:
Example:
if (localStorage.clickcount)
  {
  localStorage.clickcount=Number(localStorage.clickcount)+1;
  }
else
  {
  localStorage.clickcount=1;
  }
document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";

The sessionStorage Object

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.
The following example counts the number of times a user has clicked a button, in the current session:



Example:
if (sessionStorage.clickcount)
  {
  sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
  }
else
  {
  sessionStorage.clickcount=1;
  }
document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";




[Read More...]


HTML5 Geolocation - Locate the User's Position - Handling Errors and Rejections



Locate the User's Position
The HTML5 Geolocation API is used to get the geographical position of a user.
Since this can compromise user privacy, the position is not available unless the user approves it.

Browser Support

Internet Explorer 9, Firefox, Chrome, Safari and Opera support Geolocation.
Note: Geolocation is much more accurate for devices with GPS, like iPhone

HTML5 - Using Geolocation

Use the getCurrentPosition() method to get the user's position.
The example below is a simple Geolocation example returning the latitude and longitude of the user's position:

Example:

<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML="Latitude: " + position.coords.latitude + 
  "<br />Longitude: " + position.coords.longitude; 
  }
</script>

Example explained:
  • Check if Geolocation is supported
  • If supported, run the getCurrentPosition() method. If not, display a message to the user
  • If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter ( showPosition )
  • The showPosition() function gets the displays the Latitude and Longitude
The example above is a very basic Geolocation script, with no error handling.

Handling Errors and Rejections

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

function showError(error)
  {
  switch(error.code) 
    {
    case error.PERMISSION_DENIED:
      x.innerHTML="User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML="The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML="An unknown error occurred."
      break;
    }
  }



Error Codes:
  • Permission denied - The user did not allow Geolocation
  • Position unavailable - It is not possible to get the current location
  •  Timeout - The operation timed out

Displaying the Result in a Map

To display the result in a map, you need access to a map service that can use latitude and longitude, like Google Maps:

function showPosition(position)
{
var latlon=position.coords.latitude+","+position.coords.longitude;

var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&sensor=false";

document.getElementById("mapholder").innerHTML="<img src='"+img_url+"' />";
}


In the example above we use the returned latitude and longitude data to show the location in a Google map (using a static image).
How to use a script to show an interactive map with a marker, zoom and drag options.


Location-specific Information

This page demonstrated how to show a user's position on a map. However, Geolocation is also very useful for location-specific information.
Examples:
  • Up-to-date local information
  • Showing Points-of-interest near the user
  • Turn-by-turn navigation (GPS)

The getCurrentPosition() Method - Return Data

The getCurrentPosition() method returns an object if it is successful. The latitude, longitude and accuracy properties are always returned. The other properties below are returned if available.
PropertyDescription
coords.latitudeThe latitude as a decimal number
coords.longitudeThe longitude as a decimal number
coords.accuracyThe accuracy of position
coords.altitudeThe altitude in meters above the mean sea level
coords.altitudeAccuracyThe altitude accuracy of position
coords.headingThe heading as degrees clockwise from North
coords.speedThe speed in meters per second
timestampThe date/time of the response

Geolocation object - Other interesting Methods

watchPosition() - Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).
clearWatch() - Stops the watchPosition() method.
The example below shows the watchPosition() method. You need an accurate GPS device to test this (like iPhone):


Example:


<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.watchPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML="Latitude: " + position.coords.latitude + 
  "<br />Longitude: " + position.coords.longitude; 
  }
</script>




[Read More...]


HTML5 Canvas vs. SVG - SVG - Canvas - Comparison of Canvas and SVG



Both canvas and SVG allow you to create graphics inside the browser, but they are fundamentally different.

SVG

SVG is a language for describing 2D graphics in XML.
SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element.
In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.

Canvas

Canvas draws 2D graphics, on the fly (with a JavaScript).
Canvas is rendered pixel by pixel.
In canvas, once the graphic is drawn, it is forgotten by the browser. If its position should be changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.

Comparison of Canvas and SVG

The table below shows some important differences between canvas and SVG.
CanvasSVG
  • Resolution dependent
  • No support for event handlers
  • Poor text rendering capabilities
  • You can save the resulting image as .png or .jpg
  • Best suited for graphic-intensive games where many objects are redrawn frequently
  • Resolution independent
  • Support for event handlers
  • Best suited for applications with large rendering areas (Google Maps)
  • Slow rendering if complex (anything that uses the DOM a lot will be slow)
  • Not suited for game applications

[Read More...]


 
Payza Signup
Return to top of page Copyright © 2011 | Web Tutorial 2 Sponsored byTuli Host BD