HTML and CSS Reference
In-Depth Information
Network Type Detection and Handling
Now that we have the ability to buffer (or predictive cache) the example web app, we
must provide the proper connection detection features to make the app smarter. This
is where mobile app development gets extremely sensitive to online/offline modes and
connection speed. Enter the Network Information API. With it, you can set up an ex‐
tremely smart mobile web app.
When would this be useful? Suppose someone on a high-speed train is using your app
to interact with the Web. As the train rushes along, the network may very well go away
at various moments, and various locales may support different transmission speeds
(HSPA or 3G might be available in some urban areas, while remote areas might support
much slower 2G technologies only). Not only does the following code address connec‐
tion scenarios like this, it also:
• Provides offline access through applicationCache
• Detects if bookmarked and offline
• Detects when switching from offline to online and vice versa
• Detects slow connections and fetches content based on network type
Again, all of these features require very little code. The first step is detect the events and
loading scenarios (see ):
window . addEventListener ( 'load' , function ( e ) {
if ( navigator . onLine ) {
// new page load
processOnline ();
} else {
// the app is probably already cached and (maybe) bookmarked...
processOffline ();
}, false );
window . addEventListener ( "offline" , function ( e ) {
// we just lost our connection and entered offline mode,
// disable external link
processOffline ( e . type );
}, false );
window . addEventListener ( "online" , function ( e ) {
// just came back online, enable links
processOnline ( e . type );
}, false );
In the EventListener statements above, we must tell the code if it is being called from
an event or an actual page request or refresh. The main reason is because the body
onload event won't be fired when switching between the online and offline modes.
Search WWH ::

Custom Search