HTML and CSS Reference
In-Depth Information
!
(
/[\#]/g
).
test
(
link
.
href
)
&&
//check for an explicit class name setting to fetch this link
(
link
.
className
.
indexOf
(
'fetch'
)
>=
0
))
{
//fetch each url concurrently
var
ai
=
new
ajax
(
link
,
function
(
text
,
url
){
//insert the new mobile page into the DOM
insertPages
(
text
,
url
);
});
ai
.
doGet
();
}
}
}
};
The use of the AJAX object ensures proper asynchronous post-processing. In this ex‐
ample, you see the basic use of caching on each request and of providing the cached
objects when the server returns anything but a successful (200) response.
function
processRequest
()
{
if
(
req
.
readyState
==
4
)
{
if
(
req
.
status
==
200
)
{
if
(
supports_local_storage
())
{
localStorage
[
url
]
=
req
.
responseText
;
}
if
(
callback
)
callback
(
req
.
responseText
,
url
);
}
else
{
// There is an error of some kind, use our
//cached copy (if available).
if
(
!!
localStorage
[
url
])
{
// We have some data cached, return that to the callback.
callback
(
localStorage
[
url
],
url
);
return
;
}
}
}
}
Unfortunately, because
localStorage
uses UTF-16 for character encoding, each single
byte is stored as 2 bytes, bringing our storage limit from 5MB to 2.6MB total. Fetching
and caching these pages/markup outside of the application cache scope allows you to
take advantage of all the storage space provided by the device.
With the recent advances in the
iframe
element with HTML5, you now have a simple
and effective way to parse the
responseText
you get back from an AJAX call. There are
plenty of 3,000-line JavaScript parsers and regular expressions that remove script tags
and so on. But why not let the browser do what it does best? The next example writes
the
responseText
into a temporary hidden
iframe
. This uses the HTML5
sandbox
attribute, which disables scripts and offers many security features. (See
complete
source
.)