Saturday, December 7, 2024

HTML 5: AppCache by Example




Another new HTML 5 improvement for web developers is AppCache. While the name may not be intuitively obvious as to the role of AppCache, once you understand its purpose it makes perfect sense. With AppCache you can selectively cache in the web browser everything from pages to images to scripts to cascading style sheets. In the example and explanations to follow we will explore how AppCache works, what its limitations are, and the benefits of using it.

Setting up the Scenario

We are building a new website for a financial institution. We want to offer a loan calculator that visitors can use when they are online and offline. To that end we are implementing AppCache to allow users to access the calculator when they are offline.

The JavaScript and CSS Files

In order to easily illustrate how AppCache works we have created a JavaScript and CSS file for our application. However, instead of providing the content of the files or the files here we have instead uploaded them to our HTMLgoodies.com server. This way you can simply turn on and off your internet connection to see how your browser handles the cached information.

The Page Markup

This is the page that visitors will go to when they are looking to calculate their loan payments. It contains HTML markup, scripts for presenting results, and references to several files including our .js, .css and .manifest files. Like the JavaScript and CSS files we have uploaded this page to our servers, however, we have also included the markup here so that you can see how an AppCache manifest file is referenced within the HTML markup.

<html manifest=”HTML5_AppCache_Example.appcache”>

<head> 

    <title>HTML 5 AppCache Example – Loan Calculator</title> 

    <link href=”HTML5_AppCache_LoanCalculator.css” rel=”stylesheet” type=”text/css” /> 

</head> 

<body> 

  

<script src=”HTML5_AppCache_LoanCalculator.js” type=”text/javascript“></script> 

  

<script language=”JavaScript” type=”text/javascript“> 

    function getResult() { 

        var calculationResult = calculateLoanPayment(document.getElementById(“TextPrincipal”),document.getElementById(“TextTerm”),document.getElementById(“TextRate”)); 

        if ((calculationResult == null) || (isNaN(calculationResult)))  

        { 

            document.loanCalculator.TextCalculatedPayment.value = “Unable to calculate due to invlaid data. Please make sure initial loan amount, term (monthly), and interest rate are all numeric values.“; 

            document.getElementById(“TextCalculatedPayment”).setAttribute(“class”, “error”); 

        } 

        else  

        { 

            document.loanCalculator.TextCalculatedPayment.value = calculationResult; 

            document.loanCalculator.TextCalculatedPayment.setAttribute(“class”, “result”); 

        } 

    } 

  

</script> 

  

    <form name=”loanCalculator” method=”post”> 

        <table cellpadding=”5″ cellspacing=”0″ width=”800px”> 

            <tr> 

                <td colspan=”2″ class=”heading”> 

                    HTML 5 AppCache Loan Calculator Example</td> 

            </tr> 

            <tr> 

                <td colspan=”2″ class=”tableContent“>

                    This calculator is being used for the purposes of illustrating how HTML 5

                    AppCache works in an offline scenario.

                    The calculations that it provides are extremely simple and should not be used

                    for actual loan payment calculations.</td>

            </tr>

            <tr>

                <td align=”right” class=”tableContent“>

                    Loan Amount:</td>

                <td>

                    <input id=”TextPrincipal” size=”30″ title=”Loan Amount” type=”text”

                        class=”input” /></td>

            </tr>

            <tr>

                <td align=”right” class=”tableContent“>

                    Term (in months):</td>

                <td>

                    <input id=”TextTerm” size=”30″ title=”Loan Term” type=”text” class=”input” /></td>

            </tr>

            <tr>

                <td align=”right” class=”tableContent“>

                    Interest Rate:</td>

                <td>

                    <input id=”TextRate” size=”30″ title=”Interest Rate” type=”text”

                        class=”input” /></td>

            </tr>

            <tr>

                <td align=”right” class=”tableContent“>

                    Calculated Payment:</td>

                <td>

                    <input id=”TextCalculatedPaymentreadonly=”readonly” size=”44″

                        title=”Calculated Monthly Payment” type=”text” class=”result” /></td>

            </tr>

            <tr>

                <td>

                    &nbsp;</td>

                <td>

                    <input id=”ButtonCalculate” type=”button” value=”Calculate”

                        onclick=”getResult()” class=”tableContent” />&nbsp;

                    <input id=”ResetCalculator” type=”reset” value=”Reset” class=”tableContent” /></td>

            </tr>

        </table>

    </form>

</body>

</html>

Creating a Manifest File

Creating a manifest file is fairly easy and straightforward. There are four basic sections to a manifest file and only the CACHE MANIFEST header is actually required. Here they are with an explanation of their purpose:

CACHE MANIFEST – This is the only required piece of a manifest file and it must be the very first line of the file. The required text is CACHE MANIFEST. Below that line it is suggested that you add a comment with the date the manifest file was created/updated and/or a version number. In our example manifest file below we use both. Whatever you choose be sure to begin the line with a # sign which denotes the line as a comment. The reason for a date/version line in the file will be explained later.

CACHE – Here we list the path to each file that you want the browser to cache. Each file must be on a separate line. In our example we have added our .html page plus the supporting .js and .css files to the manifest.

NETWORK – This indicates pages that must have a network connection in order to be loaded. Basically it’s the opposite of cache and lets the browser know to never cache the page. This is most useful for pages where you are accessing data from a database or for pages where the content changes frequently. In our example we have listed a few dummy pages to show you how the NETWORK section should look. You can also add the * instead of listing pages individually which basically tells the browser to never cache pages except for the pages that you have listed in the CACHE section.

FALLBACK – This section defines a page that is displayed when any page in a defined directory has a network connection failure. An example of when this section is useful would be a customer profile area of a website whose pages are ASP.NET or PHP driven and connect to a database. You don’t want users trying to work offline because a network connection is essential for the page functionality. Instead of error messages it would be much cleaner and more professional to forward users to a page that explains that there is a network issue and the application is unavailable. In our example we list the fictitious ClientProfile directory which displays the HTML5_AppCache_Example_Offline.html page when pages in the ClientProfile directory cannot be accessed.

Our Example Manifest File Contents

CACHE MANIFEST

 # 2012-03-26 v1.0.0

 

CACHE:

/html5/HTML5_AppCache_LoanCalculator.html

/html5/HTML5_AppCache_LoanCalculator.css

/html5/HTML5_AppCache_LoanCalculator.js

 

NETWORK:

 login.aspx

 profile.aspx

 

FALLBACK:

 /ClientProfile/ /HTML5_AppCache_Example_Offline.html

Referencing the Manifest File

Now that we have a manifest file how do we reference it? We simply add a manifest attribute to the <html> element. In our example that looks like <html manifest=”HTML5_AppCache_Example.appcache”>.

Why the Comment Line is Important

The reason that you should always include a comment line in your manifest file with a date and/or version number is so that you can force the browser to update the cached information. Unless there is some change in the manifest file, a browser will continue use the cached information until the cache is cleared by the user or there is a change in the manifest file. What that means is that if you make changes to your .css file, for example, it will not be reflected on your page until your manifest file content changes forcing the browser to reload the cache. This is because the browser compares the manifest file it has cached to the manifest file it gets when the page is loaded. If they are the same the browser then loads the cached files regardless of whether the content of the files has changed on the website. So, just remember to update your manifest date and/or version number each time that you make changes to any of the cached files and your web pages will cache and display correctly.

Other Important Facts

It should also be noted that the CACHE, NETWORK and FALLBACK sections do not have to be listed in any certain order. It would be perfectly valid to list FALLBACK first and CACHE last. You should also note that there can be multiple sections, i.e. more than one CACHE section, NETWORK section, etc.

The Benefits

There are three main benefits to using AppCache. The first should be obvious, it’s faster. Since the files are already cached in memory the execution is significantly quicker. Secondly, network traffic is reduced since there is no need to pull down a cached file from the server. Lastly, it can be very useful to have certain applications be accessible both online and offline.

The Limitations

There are really only two limitations. First is the fact that some browsers put a limit on how much memory they will allot for caching files. The general consensus on the limit seems to be 5 Mb right now but that could change over time. The second is that AppCache manifest files must be served from the server with the correct mime-type or the manifest file may not be recognized by the browser. The correct mime-type is text/cache-manifest. For many servers, especially older ones, this means the mime-type may have to be manually configured.

Conclusion

This is yet another potentially useful tool from HTML 5. Despite the limitations, it can be extremely useful over a broad range of scenarios, especially with CSS and JavaScript files that apply to a number of pages on a website. Just remember to consider carefully what to cache before creating your manifest files so that you won’t exceed any browser limits and get some unexpected or unpredictable results.

Note: AppCache has been implemented in all current major browsers except Internet Explorer.

Happy coding!

 

 

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured