HTML5 Application Cache


With application cache 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

The numbers in the table specify the first browser version that fully supports Application Cache.

API
Application Cache 4.0 10.0 3.5 4.0 11.5

HTML Cache Manifest Example

The example below shows an HTML document with a cache manifest (for offline browsing):

Example

<!DOCTYPE HTML>
<html manifest="demo.appcache">

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

</html>
Try it yourself »

Cache Manifest Basics

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

<!DOCTYPE HTML>
<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"

Note A manifest file needs to be served with the correct media 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

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:

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
Note 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).


 







HTML5 Web Workers


A web worker is a JavaScript running in the background, without affecting the performance of the page.


What is a Web Worker?

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.


Browser Support

The numbers in the table specify the first browser version that fully support Web Workers.

API
Web Workers 4.0 10.0 3.5 4.0 11.5

HTML Web Workers Example

The example below creates a simple web worker that count numbers in the background:

Example

Count numbers:


Check Web Worker Support

Before creating a web worker, check whether the user's browser supports it:

if(typeof(Worker) !== "undefined") {
    // Yes! Web worker support!
    // Some code.....
} else {
    // Sorry! No Web Worker support..
}

Create a Web Worker File

Now, let's create our web worker in an external JavaScript.

Here, we create a script that counts. the script is stored in the "demo_workers.js" file:

var i = 0;

function timedCount() {
    i = i + 1;
    postMessage(i);
    setTimeout("timedCount()",500);
}

timedCount();

The important part of the code above is the postMessage() method - which is used to post a message back to the HTML page.

Note: Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.


Create a Web Worker Object

Now that we have the web worker file, we need to call it from an HTML page.

The following lines checks if the worker already exists, if not - it creates a new web worker object and runs the code in "demo_workers.js":

if(typeof(w) == "undefined") {
    w = new Worker("demo_workers.js");
}

Then we can send and receive messages from the web worker.

Add an "onmessage" event listener to the web worker.

w.onmessage = function(event){
    document.getElementById("result").innerHTML = event.data;
};

When the web worker posts a message, the code within the event listener is executed. the data from the web worker is stored in event.data.


Terminate a Web Worker

When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated.

To terminate a web worker, and free browser/computer resources, use the terminate() method:

w.terminate();

Reuse the Web Worker

If you set the worker variable to undefined, after it has been terminated, you can reuse the code:

w = undefined;

Full Web Worker Example Code

We have already seen the Worker code in the .js file. Below is the code for the HTML page:

Example

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<br><br>

<script>
var w;

function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("images/demo_workers.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result") .innerHTML = "Sorry! No Web Worker support.";
    }
}

function stopWorker() {
    w.terminate();
    w = undefined;
}
</script>

</body>
</html>
Try it yourself »

Web Workers and the DOM

Since web workers are in external files, they do not have access to the following JavaScript objects:


 







HTML5 Server-Sent Events


Server-Sent Events allow a web page to get updates from a server.


Server-Sent Events - One Way Messaging

A server-sent event is when a web page automatically gets updates from a server.

this was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.

Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.


Browser Support

The numbers in the table specify the first browser version that fully support server-sent events.

API
SSE 6.0 Not Supported 6.0 5.0 11.5

Receive Server-Sent Event Notifications

The EventSource object is used to receive server-sent event notifications:

Example

var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
    document.getElementById("result").innerHTML += event.data + "<br>";
};
Not Available

Example explained:


Check Server-Sent Events Support

In the tryit example above there were some extra lines of code to check browser support for server-sent events:

if(typeof(EventSource) !== "undefined") {
    // Yes! Server-sent events support!
    // Some code.....
} else {
    // Sorry! No server-sent events support..
}

Server-Side Code Example

For the example above to work, you need a server capable of sending data updates (like PHP or ASP).

The server-side event stream syntax is simple. Set the "Content-Type" header to "text/event-stream". Now you can start sending event streams.

Code in PHP (demo_sse.php):

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: the server time is: {$time}\n\n";
flush();
?>

Code in ASP (VB) (demo_sse.asp):

<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: the server time is: " & now())
Response.Flush()
%>

Code explained:


the EventSource Object

In the examples above we used the onmessage event to get messages. But other events are also available:

Events Description
onopen When a connection to the server is opened
onmessage When a message is received
onerror When an error occurs