Rss Feed Like Us on facebook Google Plus
Showing posts with label web. Show all posts
Showing posts with label web. Show all posts

March 1, 2013

New Faster & Lighter Facebook Like Box

If you have the Facebook Like box embedded in your website, the good news is that the plugin should have little impact on the performance, or page speed, of your pages.
Stoyan Stefanov of the Facebook engineering team shares that the updated Like box is 2-4x faster and is considerably lighter than the previous version. The Facebook Like plugin now loads in 0.5 seconds, as opposed to 2.3 seconds and while the previous version was 245KB in size, it now weighs a mere 46KB.
Facebook Like Box - Old
Earlier, Facebook Like box made 24 web requests and would load in 2.4 seconds
Facebook improved the performance of the plugin by switching to inline CSS styles (as opposed to using external stylesheets) and by squeezing multiple scripts into one – the plugin thus has to make fewer web requests.
Facebook Like Box - New
Facebook Like box now loads in .7 seconds and makes just 13 requests (for photos)
How do you get the faster Facebook Like box for your website? First, does the Facebook embed code on your website look anything like this?
XFBML version (old)
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<fb:fan stream="false" name="PAGE_NAME"></fb:fan>
IFRAME version (old):
https://www.facebook.com/plugins/fan.php?connections=10&name=PAGE_NAME
If your embed codes are different, you are covered as Facebook will automatically serve you the improved Like box. Else, you are using the older /deprecated version of the Facebook Like box  so head over to developers.facebook.com and generate the new embed codes.
Read More

February 28, 2013

HTML 5 Web Storage

In this article we are going to see some good stuff and example of Web Storage. We are developing TODO list for the individual. All the TODO data will be stored in your local browser.
Learning any new stuff with example always helps us to understand it very deeply. So here we have used TODO list example.

Above screenshot is what we are going to develop. Let me give you basic idea about our requirement.
1) Notes should be stored and retrieved very quickly.
2) Notes should be filter with Category.
3) Notes should be color with different category
4) Notes should be removed if user wants.

Use of Web Storage:

Web storage can hold data in MBs. It can hold 2.5 to 10 MB of data depending on browsers. you can even test yourself. Although i have never tried it but some wiki documents provides such data.
Let we start with providing you basic operations like add/update/delete on web storage data. After getting idea about basic concept we will create simple TODO application as shown in above screen. We have used CSS and Javascript to make it like professional application. We will take code snippet from our example to present basic operations.
1) Add new item in Web Storage
 var storage = JSON.parse(localStorage.getItem('ToDoList')); 
            if (!storage) { 
                storage = []; 
                localStorage.setItem('ToDoList', JSON.stringify(storage));
            } 
As you can see in above code we have used localStorage.getItem to check if 'ToDoList' key is exist in the local storage for particular browser.
Secondly, We are using JSON.parse to get array data. We need to store TODO category and information. we have used single dimensional array for datastorage. JSON.parse is used to convert array data into string repesentation. AndJSON.Stringify can be used to convert array into string representation to store it back in local storage.
you need to keep it in mind that Web storage can hold only string data.
2) Update item in Web Storage
localStorage.setItem method in the first code snippet can be used to update item in the web storage. if you have existing key ToDoList in the web storage then it will update it's data specified by second parameter.
3) Remove item in Web Storage
var storage = JSON.parse(localStorage.getItem('ToDoList'));
storage.splice(itemId - 1, 2);
localStorage.setItem('ToDoList', JSON.stringify(storage));  
In our case we need to remove item from the array list. we have one dimensional array to store category and it's note value. category will be stored in all odd indexes while todo notes will be stored in all even indexes. We need to remove two item from array to remove particular notes.
In given example we have used splice to remove from the array. first parameter of splice define index from where we need to remove item while the second parameter defines number items we need to be removed.
And at last we have update array list. if we are not using array and if we have single key/value pair for storing in web storage then we can use removeItem method of localStorage.
Hope this information is enough to start working with web storage of html5. Now we will see the code for creating your personal todo list.

Important Code:

        function loadNotes() {
            var storage = JSON.parse(localStorage.getItem('ToDoList'));
            if (!storage) {
                storage = [];
                localStorage.setItem('ToDoList', JSON.stringify(storage));
            }
            var displayArea = document.getElementById("displayArea");
            var currentFilter = document.getElementById("slSearchCategory").value;
            var innerDiv = "";
            for (var i = storage.length - 1; i >= 0; i = i - 2) {
                if (currentFilter == storage[i - 1] || currentFilter == "") {
                    var todoColor = 'AD7460';
                    switch (storage[i - 1]) {
                        case 'HR':
                            todoColor = '90CA77';
                            break;
                        case 'Payroll':
                            todoColor = '81C6DD';
                            break;
                        case 'Sales':
                            todoColor = 'F9D654';
                            break;
                        case 'Personal':
                            todoColor = 'AD7460';
                            break;
                        default:
                            todoColor = 'AD7460';
                            break;
                    }
                    innerDiv += "<div class='displayToDo'  style='background:#" + todoColor + "'><input type='image' src='delete.png' width='15px' height='15px' onclick='removeMe(" + i + ")' /> Category : " + storage[i - 1] + " <hr /> " + storage[i] + "</div>";
                }
            }   
 
            if (innerDiv != undefined) {
                displayArea.innerHTML = innerDiv;
            }
            else {
                displayArea.innerHTML = "";
            }   
First of all we are taking all the todo that we have stored in the array called ToDoList. Once we have data we are ready to render data on the html page. we have one static div with id='displayArea'. Then for each item in the array we will iterate and check for the category of particular todo item. According to category we will assign hex color value into one variable. once we are ready with the color hex code we are dynamically creating html divs. Once we have ready html code we can set as innerHtml.
At last we have added condition to check if innerDiv value is updated with some dynamic data or not. In case of empty web storage array innerDiv value will be undefined.
function SaveNotes() {
            var category = document.getElementById("slSearchCategory").value;
            var todo = document.getElementById("txtToDo").value;

            if (category == "") {
                alert("Please select Category.");
                return;
            }

            var storage = JSON.parse(localStorage.getItem('ToDoList'));
            var arrayLength = storage.length;

            storage[arrayLength] = category;
            storage[arrayLength + 1] = todo;
            localStorage.setItem('ToDoList', JSON.stringify(storage));
            category = "";
            loadNotes();
            clearNote();
        } 
Above Javascript function will be called when you click on the 'Add TODO' button. We need the category and todo note as input from the dropdown list and textArea respectively. After getting data we have added validation to check if user have clicked button without selecting correct category. Once you have correct data you are ready to add new item into the web storage array. And last two steps is to load Notes again and Clear the TextArea(todo that you have entered).
We have also used some CSS3 features to display round corner div. this will really help to designer. when we do not have CSS3 we need to do a lot of work to handle such situation.
 .displayToDo
        {
            -moz-border-radius: 10px<span class="code-none">;
            border-radius<span class="code-none">: 10px<span class="code-none">;
            height<span class="code-none">: Auto<span class="code-none">;
            width<span class="code-none">: 200px<span class="code-none">;
            color<span class="code-none">: #ffffff<span class="code-none">;
            float<span class="code-none">: left<span class="code-none">;
            margin<span class="code-none">: 10px<span class="code-none">;
            padding<span class="code-none">: 10px<span class="code-none">;
        <span class="code-none">} </span></span></
As you can see in the above CSS code we have displayToDo CSS class. if you have observed we are applying this CSS class to dynamically generated div. This style will be applied immediately when DOM will be updated with given innerHTML dynamic text. 
Read More

February 25, 2013

Build a Web Application with HTML 5

Introduction

HTML5 is the fifth revision and the newest version of the HTML standards. Previous version (HTML 4.01) was released in 1999. In 2006, WHATWG (Web Hypertext Application Technology Working Group) & W3C (World Wide Web Consortium) came together to define the new version of HTML. Earlier, WHATWG was working with web forms and applications, and W3C was working with XHTML 2.0.
They discussed and layed out HTML Design Principles. They were addressed towards better experience for user and easy adoption for developer which would be independant of device and plugins with a graceful fallback mechanism. HTML5 specifications were finalized on 17th December 2012 last year.

Tools

HTML5 is still a work in progress. Browsers are implementing HTML5 specifications as per their individual plans, thus we have various level of support on different browsers.
In order to know what features are supported by a particular browser, few websites shares the information in detail about HTML5 compatibility with different versions of a browser:
  • HTML5 Test - provides a HTML5 score with detail on what can be used
  • Can I Use - provides a table comparison of major browsers for different features
Current support scores for various browsers are:
    
In order to develop for various browsers, we can use User Agent Switcher:
In order to have a fallback plan, while developing, we need to first check if a particular HTML5 feature is supported on the browser being used. Traditional approach of creating the dynamic element in JavaScript and checking for any of it's properties existence is good enough. Another option could be to use an open source JavaScript library Mordernizr(MIT-licensed). It can be used in the following manner:
<script src="modernizr.min.js"></script>
<script type="text/javascript">
if (Modernizr.canvas) {
        // Congrats! Canvas is supported on your browser.
} else {
        // Sorry! No native canvas support available on your browser.
}
</script>
In order to have a look at internal details of the web page, explore and understand what's happening on client side in browser, Developer Tools of the browsers are extremely helpful:
    

Structure

HTML5 is designed such that it is not based on SGML (Standard Generalized Markup Language), thus they does not requirea reference to a DTD (Document Type Definition). So, for passing the HTML version instruction to web browser, following works:
<!DOCTYPE HTML>
A new short way to declare character encoding in the webpage:
<meta charset="utf-8">
Moving forward, HTML5 has new web page elements that adds semantic to the page. Like:
  • Header
  • Nav
  • Footer
  • Section
  • Article
Following is the sample web page structure comparison with HTML4 design:
   
Here is the code snippet of an example using new structural semantics:
<hgroup>
    <h1>Penning Everything Interesting…</h1>
</hgroup>
<article id="MyBlog">
    <header>
        <h2>My first blog entry!</h2>
    </header>
    <p>I was thinking what to write about. I read few articles at times that I feel like sharing across, probably ...</p>
    <br/>
    <footer>
    <section>
        <h4>One Thought on 'My first blog entry…'</h4>
        <article id="comment_1">
            <link href="#comment_1" />
            <h5>Comment by: Guruji</h5>
            <p>Very well written. Love the enthu and energy you have for sharing your knowledge...</p>
        </article>
        <article id="comment_2">
            <link href="#comment_2" />
            <h5>Comment by: SuperStar</h5>
            <p>Looks like a good start...Good going!</p>
        </article>
    </section>
    </footer>
</article>
Along with addition, few elements & attributes are deprecated and are no more thereas per specification:
These above tags are not to be used by developer. Still, it has been decided that User agents will have to support them.

Forms

Various new form based tags and attributes has been defined in HTML5, like:
  • input types and attributes
    • email
    • url
    • number
    • date time
    • search
    • range
    • color
  • control elements
    • datalist
    • keygen
    • output
  • attributes
    • spellcheck
    • autofocus
    • list
    • required
    • placeholder
    • min and max
    • multiple
  • events
    • orientationchange
    • resize
    • online
    • offline
  






Few samples using them:
email:    <input type="email" multiple required autofocus placeholder="sample@sample.com" />                
url:    <input type="url" />
number:    <input type="number" />
date time: <input type="date"/>
   <input type="time"/>
search:    <input type="search"/>
range:    <input type="range" max="100" min="80" step="2" title="Your AES score" name="rscore"/>
   <output name="score">90</output>
color:    <input type="color"/>
datalist:  <input type="text" id="somenames" list="fullList" />
   <datalist id="fullList">
       <option value="Sandeep">
       <option value="Deepak">
       <option value="Sandy">
       <option value="Deepu">                                            
   </datalist>
spellcheck:<input type="text" spellcheck="false" placeholder="Without Spellcheck">
   <input type="text" spellcheck="true" placeholder="With Spellcheck">
Further, HTML5 has improved way of finding controls with new selectors. Just like jQuery selectors, HTML5 has two new selectors that help in finding the needed control quickly:
  • document.querySelector() - Return the first element in the page which matches the specified selector rules
    // Returns the first element in the document with the class "myclass"                              
    var el = document.querySelector(".myclass");
  • document.querySelectorAll() - Returns all elements which match the specified rules
    // Returns the list of all the element in the document with the class "myclass"
    var els = document.querySelectorAll(".myclass");

Drag & Drop

HTML5 has made drag-drop feature as part of standards and any element can be made draggale and then dragged to defined location. Attributes, methods and events related to it are:
  
  • draggable
  • ondragstart
  • setData
  • getData
  • ondragover
  • ondrop
Sample code for above logo drag-drop will look like:
function allowDropDragOver(e) {
    e.preventDefault();
}

function dragStart(e) {
    e.dataTransfer.setData("dragItemID", e.target.id);
}

function dropIt(e) {
    e.preventDefault();
    var dataId = e.dataTransfer.getData("dragItemID");
    e.target.appendChild( document.getElementById(dataId));
}

<table>
    <tr>
        <td>
            <div id="bin1" ondrop="dropIt(event)" ondragover="allowDropDragOver(event)" class="dragDropBin">
                <img id="dragImage" src="../Images/HTML5LogoSmall.png" 
                     draggable="true" ondragstart="dragStart(event)" class="dragImage">
            </div>
        </td>
        <td><div id="bin2" ondrop="dropIt(event)" ondragover="allowDropDragOver(event)" class="dragDropBin"></div></td>
    </tr>
    <tr>
        <td><div id="bin3" ondrop="dropIt(event)" ondragover="allowDropDragOver(event)" class="dragDropBin"></div></td>
        <td><div id="bin4" ondrop="dropIt(event)" ondragover="allowDropDragOver(event)" class="dragDropBin"></div></td>
    </tr>
</table>

Audio & Video

This is one of the major features of HTML5 that has brought a big difference in having audio or video feature on a webpage. They will kill usage of plugins (like flash or silverlight) just based on performance. Guess what, it is super easy to implement too with just a few lines of code. Attributes, methods and events related to it are:
  • Attributes & Methods
    • play(): To play the media
    • pause(): To pause the media
    • canPlayType(): To check if browser can play a certain media resource type
    • src: Path of the media file. One can also use the <source> element
    • autoplay: To play the media automatically
    • controls: To display the controls (play/pause/volume/etc) on the media
    • loop: To play in loop
    • muted: To mute the volume
    • playbackRate: To vary the speed of the media
  • Events
    • play: raised when the media is played
    • pause: raised when the media is paused
    • timeupdate: raised when the current playback position has changed
    • volumechange: raised when the volume of the media has changed
    • ratechange: raised when the playback rate of the media has changed
    • ended: raised when the media has finished playing
    • seeking: raised when the end user is seeking in the media
    • seeked: raised when the seeking attribute has changed to false
  
Currently, there are defined formats supported by different browsers. HTML5 based supported formats are:
  • Audio: MP3, Wav, and Ogg
  • Video: MP4, WebM, and Ogg
Sample code for audio & video implementation looks like:
<audio id="sampleAudio" controls>
    <source src="../Files/AudioSample.mp3">
    <source src="../Files/AudioSample.wav">
    <source src="../Files/AudioSample.ogg">  
    Your browser does not support the audio element.          
</audio>

<video id="sampleVideo" controls src="../Files/VideoSample.mp4">
     <track src="../Files/sampleSubtitles.vtt" srclang="en" kind="subtitles" label="English subtitles">
    Your browser does not support the audio element.
</video>

<!-- For runtime button based operations -->
function CMute(controlId) {
    $(controlId).attr('muted', true);
}

function CUnMute(controlId) {
    $(controlId).attr('muted', false);
}

function CPause(controlId) {
    if (!($(controlId).get(0).paused))
        $(controlId).get(0).pause();
}

function CPlay(controlId) {
    $(controlId).get(0).play();
}

function CFullScreen(controlId) {
    // Only Chrome code currently. 
    $(controlId)[0].webkitRequestFullScreen();
}

<input type="button" value="Mute" onclick="CMute(sampleAudio);"/>
<input type="button" value="Unmute" onclick="CUnMute(sampleAudio);"/>
<input type="button" value="Pause" onclick="CPause(sampleAudio);"/>
<input type="button" value="Play" onclick="CPlay(sampleAudio);"/>

Geo Location

HTML5 Geolocation is used to locate a user's geographical position. Since this is related to specific individual usage, it can compromise user privacy. Thus, user permission is necessary in order to locate the position. In order to use Geolocation, we would need to know about navigator.geolocation object, it's methods and parameters:
  • Methods
    • getCurrentPosition : get's location once
    • watchPosition : regularly keeps polling
    • clearWatch : stop's watching position
  • Parameters
    • position
      • coords (Coordinates) : contains information on user location
        • latitude
        • longitude
        • altitude
        • accuracy
        • altitudeAccuracy
        • speed
        • heading
      • timestamp (DOMTimeStamp) : time when user location was obtained
    • PositionError : error callback object argument
      • UNKNOWN_ERROR = 0
      • PERMISSION_DENIED = 1
      • POSITION_UNAVAILABLE = 2
      • TIMEOUT = 3
      • code
      • message
    • PositionOptions : specifies options when getting user location
      • enableHighAccuracy
      • timeout
      • maximumAge
  



Sample code for GeoLocation - Latitude & Longitude, looks like:
// navigator.geolocation.getCurrentPosition(success_callback, error_callback, {other parameters}); 
// The watchPosition() function has the same structure as getCurrentPosition()
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(updateLocation, handleLocationError, {
            timeout: 1000000,
            maximumAge: 1000,
            enableHighAccuracy: false
        });
    }
    else {
        document.getElementById("supportstatus").innerHTML = "HTML5 Geolocation is not supported in your browser.";
    }
}

function updateLocation(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    var timeTaken = new Date(position.timestamp);
    ...
}

function handleLocationError(error) {
    switch(error.code)
    {
        ...
    }
}
Sample code for GeoLocation - Map display, looks like:
<div id="mapView" class="mapDimension1"></div>

// include the Maps API JavaScript using a script tag.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

// navigator.geolocation.getCurrentPosition
function showMap() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showMapLocation, handleLocationError, {
            timeout: 1000000,
            maximumAge: 1000,
            enableHighAccuracy: true
        });
    }
}

// create an object literal to hold map properties and create a "map" object & "marker" objects
function showMapLocation(position) {
    var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var myOptions = {
        zoom: 16,
        center: latlng,
        mapTypeControl: false,
        navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("mapView"), myOptions);

    var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: "You are here! (Accuracy: " + position.coords.accuracy + " meter radius)"
        });
}

Web Storage

HTML5 provides better local storage within the browser. Currently, we use cookies for storing information on client browser but with few limitations like they are slow, unencrypted, limited to about 4KB & need to be included with every HTTP request. Web Storage is more secure and faster. It has good storage space (~5MB) on the client without affecting the website's performance. It persists and is transmitted to the server only when asked. Currently, it supports two types of storage:
  • localStorage: stores data with no expiration date
    • Key/Value pair storage system
    • Shared between window/tab for a same domain
    • Data available until explicitly deleted by the user
  • sessionStorage: stores data for one session
    • Key/Value pair storage system
    • Specific to particular window/tab
Web Storage follows the storage interface that exposes API to create, read, update or delete data on the client side:
  • getItem(DOMString key) : Get the value of an item identified by its key
  • setItem(DOMString key, any data) : used to create or modify an item
  • removeItem(DOMString key) : Delete an item identified by its key
  • clear() : Delete all items
  • length : Number of items.
  • key(unsigned long index) : Get the key of an item with a zero based index
  
Sample code for implementing the web storage looks like.
function SaveToSessionStorage() {
    window.sessionStorage.mySessionKeyX = 'Saved Directly in Session';
    window.sessionStorage.setItem("mySessionKeyY" ,"Saved Using Set Item");
}

function SaveToLocalStorage() {
    window.localStorage.myLocalKeyA = 'Saved Directly in Local';
    window.localStorage.setItem("myLocalKeyB", "Saved Using Set Item");
}

function GetFromSessionStorage() {
    alert("Value X: " + window.sessionStorage.getItem("mySessionKeyX"));
}

function GetFromLocalStorage() {
    alert("Value B: " + window.localStorage.getItem("myLocalKeyB"));
}

function RemoveFromSessionStorage() {
    window.sessionStorage.removeItem("mySessionKeyX");
}

function RemoveFromLocalStorage() {
    window.localStorage.removeItem("myLocalKeyB");
}

function clearAll() {
    localStorage.clear();
    sessionStorage.clear();
}

Web Workers

HTML5 Web Workers is a JavaScript script that runs in the background after being executed from a webpage. It runs independently from other userscripts without affecting the performance of the page.
When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. Web Workers allows to perform tasks in a background process in parallel of the main browser process. Thus the page is responsive even when a worker is running. Since, web workers are in external files, they cannot access the following JavaScript objects:
  • window object
  • document object
  • parent object
  
Sample code to implement workers would look like:
// create a new Worker object 
var worker = new Worker('WebWorkerSample.js');

// start it by calling the postMessage() method
worker.postMessage(); 

// Communication between a worker and its parent page is done using an event model via postMessage() 
// Main script:
worker.addEventListener('message', function(e) {
    console.log('Worker said: ', e.data);
}, false);

//Internal Script (the worker):
self.addEventListener('message', function(e) {
    self.postMessage(e.data);
}, false);

Web Socket

HTML5 Web Socket provides a two-way communication over one TCP connection (socket). The WebSocket API standards are defined by the W3C (World Wide Web Consortium), and the WebSocket protocol has been standardized by the IETF (Internet Engineering Task Force). For it, new protocols are introduced - ws: & wss:
It has simplified complexities around client-server communication. In order to establish a connection between client and server, for the first time when the request is sent to server, it is sent as an upgrade request from a HTTP call. Once it is upgraded, and handshake is successful, client and server can talk to each other using frames (2 bytes). Server notifies the client of new messages. General use-case of it is:
  • create web socket
  • define event listeners
  • send message
Attributes, methods and events related to it are:
  
  • readyState
  • bufferedAmount
  • onopen
  • onmessage
  • onclose
  • onerror
  • send()
  • close()
Sample code related to this feature looks like:
function WebSocketTest() {
    if ("WebSocket" in window) {
        // Open a Web Socket
        var ws = new WebSocket("ws://myServer/HTML5Demo/");
        ws.onopen = function () {
            // Send data
            ws.send("Message sent to server");
            alert("Message was sent to server.");
        };
        ws.onmessage = function (evt) {
            //Recieve data
            var receivedmsg = evt.data;
            alert("Message is received from server"+ receivedmsg);
        };
        ws.onclose = function () {
            // Close a Websocket
            alert("Connection is closed.");
        };
        ws.onerror = function (evt) {
            // Log Error
            alert("ERROR!!! " + evt.message);
        };
    }
}
It is efficient, has low latency (almost instant) and size. Scalable and real time applications can be easily made based on it.

Canvas

Canvas is another feature of HTML5 that is used to draw graphics on a webpage at runtime. Canvas only the container of the graphics, the whole drawing is done via JavaScript. Thus, it is mandatory to define ID, height & width of the canvas. It has methods for drawing 2-D shapes, texts, images using Paths.
General use-case of it is:
  • define canvas element
  • get 2-D context
  • draw
Canvas provides methods which allow modifications to the transformation matrix:
  • save() & restore() - to save and restore different transformation states
  • translate() - to translate the HTML5 Canvas context
  • rotate() - to rotate the HTML5 Canvas
  • scale() - to scale the HTML5 Canvas
  
SVG (Scalable Vector Graphics) is another alternative. It is vector-based, relies on files whereas Canvas manipulates pixels, uses pure scripting. SVG has slower rendering due to SVG's integration into the DOM. Thus, probably not a good option for dynamic applications like games. Depending on the type of work, one need to select which to use.
Sample code related to same looks like:
// Define Canvas tag
<canvas id="myCanvas" width="200" height="100"></canvas>

// Access in JavaScript to draw in it at runtime
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle='Red';
context.fillRect(0,0,150,75);
context.beginPath();
context.moveTo(150, 10);
context.arcTo(80, 45, 3, 200, 90);
context.fillStyle = 'Yellow';
context.fill();
context.strokeStyle = 'Purple';
context.stroke();
context.closePath();

Offline Application

HTML5 Offline is another major feature that helps in browsing a web application even when there is no network connection. Web application has a reference to a manifest file that holds the information about the files that needs to be cached and kept, not to be cached and fallback rules for non cached files. Local copies are cached and kept without any expiration rule. If application finds any change in manifest when it goes online,  local files are updated to make it up-to-date. In absence of network connection (an onLine flag present in DOM tells it), webpages and related files are served from the local cached copies.
Sample Cache Manifest file looks like:
CACHE MANIFEST
# Cache manifest – version & date
# version 2.1.24
# 02.01.2013


# Cache – resources to cache with html page
CACHE:
Cache-Control: no-cache, private
Styles/Site.css
Images/HTML5.png
Scripts/jquery-1.4.1.min.js 
Scripts/jquery-1.4.1-vsdoc.js 
Scripts/Utilities.js 
Scripts/OfflineApp.js
offline.manifest
# Images/HTML5LogoSmall.png



# Network – files that will not be cached and will always be online
# Following resources require network connection.
# * - it’s a special flag (meaning all resources that are not cached will require a connection.)
NETWORK:
*


# Fallback – display for all uncached pages/resources [precedence below Network]
# FALLBACK:
Images/ShowFullscreen.png
#site/images/ images/offline.jpg
#*.html offline.html
ApplicationCache has various states that tells the status of the cache based on the manifest file:
  • 0 UNCACHED : cache is empty
  • 1 IDLE : cache is latest
  • 2 CHECKING : checking for a new updated version of the cache
  • 3 DOWNLOADING : downloading the new cache
  • 4 UPDATEREADY : ready to be used
  • 5 OBSOLETE : cache is marked obsolete
Sample code for tracking Offline capability is like:
// offline.appcache manifest file reference in the webpage
// <html lang="en" manifest="<%=ResolveClientUrl("offline.appcache")%>">

var cacheStatusMessages = [];
cacheStatusMessages[0] = 'uncached';
cacheStatusMessages[1] = 'idle';
cacheStatusMessages[2] = 'checking';
cacheStatusMessages[3] = 'downloading';
cacheStatusMessages[4] = 'updateready';
cacheStatusMessages[5] = 'obsolete';


var appCache = window.applicationCache;
appCache.addEventListener('cached', logEvent, false);
appCache.addEventListener('checking', logEvent, false);
appCache.addEventListener('noupdate', logEvent, false);

appCache.addEventListener('downloading', logEvent, false);
appCache.addEventListener('progress', logEvent, false);
appCache.addEventListener('updateready', function() {
    window.applicationCache.swapCache();
    console.log('Update was ready. Swap Cache done.');
}, false);

appCache.addEventListener('obsolete', logEvent, false);
appCache.addEventListener('error', logEvent, false);

function logEvent(e) {
    var online, status, type, message;
    online = (navigator.onLine) ? 'yes' : 'no';
    status = cacheStatusMessages[appCache.status];
    type = e.type;
    
    message = 'online: ' + online;
    message += ', event: ' + type;
    message += ', status: ' + status;

    console.log(message);

    if (type == 'obsolete')
        alert('Manifest got deleted. Offline will not work anymore.');
    if (type == 'error')
        alert('Error:' + e.message);
}

Device Support

HTML5 have defined ways to support multiple devices. It's a key to mobile page optimization.
  • Viewport Meta Tag - it controls browsers page display, by telling the browser how content should fit on the device's screen. Further, it informs the browser that the site is optimized for mobile devices. Sample use:
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=yes"/>
  • CSS Media Queries - these are media based stylesheets, that enables the content's presentation to be customized to a specific range of output devices without having to change the content itself.
    • External stylesheet :
      <link rel="stylesheet"  media="handheld, only screen and (max-device-width: 320px)" href="phone.css">
      <link rel="stylesheet"  media="only screen and (min-width: 641px) and (max-width: 800px)" href="ipad.css">
    • Within the <style> element (or in css file) as a media rule:
      @media only screen and (max-width: 480px){
         /* rules defined inside here are only applied to browsers that support CSS media queries */ 
         /* and the browser window is 480px or smaller */
      }
    • Imported stylesheet within the <style> element:
      @import "smallscreen.css" only screen and (max-width: 480px);
Read More

© 2011-2016 Techimpulsion All Rights Reserved.


The content is copyrighted to Tech Impulsion and may not be reproduced on other websites.