Expand your HTML skills through an MDN Fellowship - Apply by April 1 http://mzl.la/MDNFellowship

mozilla

Revision 348045 of Usando caché de aplicaciones

  • Enlace amigable (slug) de la revisión: Recursos_offline_en_firefox
  • Título de la revisión: Recursos en modo sin conexión en Firefox
  • Id de la revisión: 348045
  • Creada:
  • Creador: MPoli
  • ¿Es la revisión actual? No
  • Comentario

Contenido de la revisión

Introducción

HTML5 proporciona un mecanismo de caché de aplicación que permite que las aplicaciones basadas en la web se ejecuten sin conexión. Los desarrolladores pueden usar la interface de Caché de apliaciones (AppCache) para especificar los recursos que el navegador debería guardar en caché y tener disponibles para los usuarios cuando no estén conectados. Las aplicaciones que están en caché se cargan y funcionan correctamente aunque los usuarios hagan clic en el botón recargar cuando no están conectados.

Usar el caché de aplicaciones le da a la aplicación los siguientes beneficios:

  • Navegación sin conexión: los usuarios pueden navegar un sitio aún cuando no estén conectados.
  • Velocidad: los recursos en caché son locales, y por lo tanto, se cargan más rápido.
  • Carga al servidor reducida: el navegador solamente descarga desde el servidor recursos que han cambiado..

¿Cómo funciona el caché de aplicaciones?

Habilitando caché de apliaciones

Para habilitar el caché de apliaciones, debe incluir el atributo {{htmlattrxref("manifest", "html")}} en el elemento {{HTMLElement("html")}} en las páginas de sus aplicaciones, como se muestra en el siguiente ejemplo:

<html manifest="ejemplo.appcache"> 
  ...
</html>

El atributo manifest referencua un archivo manifiesto de cache, que es un archivo de texto que lista los recursos (archivos) que el navegador deberá guardar en caché para la aplicación.

Debería incluir el atributo manifest en cada página de la aplicación que quiera guardar en caché. El navegador no guardará páginas que no contengan el atributo  manifest, a menos que esas páginas estén específicamente listadas en el archivo de manifiesto en sí mismo. No es necesario listar todas las páginas que se quieran guardar en caché en el archivo de manfifesto, el navegador implícitamente agrega cada página que el usuario visite y tenga el atributo manifest establecido para caché de aplicación.

Algunos navegadores (ej. Firefox) muestran una notificación la primera vez que un usuario carga una aplicación que usa caché de aplicaciones La barra de notificaciones muestra un mensaje parecido a :

Este sitio web (www.ejemplo.com) está pidiendo guardar datos en su equpo para suar sin conexión. [Permitir] [Nunca para este sitio] [No por ahora]

El término "offline(-enabled) applications" a veces se refiere específicamente a aplicaciones a las que el usuario ha permitido que usen capacidades sin conexión.

Cargando documentos

Es uso de caché de aplicaciones modifica el proceso normal de la carga de un documento:

  • Si existe caché de aplicaciones, el navegador carga el documento y sus recursos asociados directamente desde ahí, sin acceder a la red. Esto acelera el tiempo de carga del documento.
  • El navegador entonces verifica si hubo actualizaciones al manifiesto de caché en el servidor.
  • Si el manifiesto de caché fue actualizado, el navegador descarga la nueva versión del archivo y de los recursos listados en él. Esto se realiza en segundo plano y no afecta el rendimiento de forma significativa.

El proceso para cargar documentos y actualizar el caché de aplicaciones está especificado con gran detalle aquí debajo:

  1. Cuando el navegador visita un documento que incluye el atributo manifest, si no existe caché de apliaciones, el navegador carga el documento y baja todas las entradas listadas en el archivo de manifiesto, creando la primera versón de caché de aplicaciones. 
  2. Posteriores visitas a ese documento causan que el navegador cargue el documento y otros archivos especificados en el manifiesto desde el caché de aplicaciones (no desde el servidor).  Además, el navegador envía un evento checking al objeto window.applicationCache y descarga el archivo de manifiesto, siguiendo las reglas de caché HTTP apropiadas.
  3. Si la copia del manifiesto actualmente en caché está actualizada, el navegador envía un evento noupdate al objeto applicationCache y el proceso de actualización está completo. Hay que tener en cuenta que si se cambia en el servidor cualquier recurso en caché, se deberá cambiar también el archivo de manifiesto, para que el navegador sepa que deberá descargar los recursos nuevamente.
  4. Si el archivo de manifiesto ha cambiado, todos los archivos listados en el manifiesto—así como los que se agregaron al caché llamando applicationCache.add()—se descargarán en un caché temporario, siguiendo las reglas de caché  HTTP apropiadas. Para cada archivo descargado en este caché temporario, el navegador envía un evento progress al objeto applicationCache. Si ocurre cualquier error, el navegador envía un evento error y la actualización se detiene.
  5. Una vez que todos los archivos han sido recuperados exitosamente, son movidos al caché sin conexión real automáticamente y un evento cached es enviado al objeto applicationCache. Como el documento ya ha sido cargado en el navegador desde caché, la actualización no se mostrará hasta que el documento sea recargado (ya sea manualmente o por programa).

Ubicación del almacenamiento y limpiando el caché sin conexión

En Chrome se puede limpiar el caché sin conexión seleccionando "Clear browsing data..." en las preferencias o visitando chrome://appcache-internals/. Safari tiene una configuración similar"Vaciar cache" en sus preferencias, pero se requiere el reinicio del navegador.

En Firefox, el caché sin conexión se guarda en un lugar separado del perfil de Firefox profile—cerca del caché de disco regular:

  • Windows Vista/7: C:\Users\<username>\AppData\Local\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache
  • Mac/Linux: /Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache

In Firefox the current status of the offline cache can be inspected on the about:cache page (under the "Offline cache device" heading). The offline cache can be cleared for each site separately using the "Remove..." button in Tools -> Options -> Advanced -> Network -> Offline data.

Prior to Firefox 11, neither Tools -> Clear Recent History nor Tools -> Options -> Advanced -> Network -> Offline data -> Clear Now cleared the offline cache. This has been fixed.

See also clearing the DOM Storage data.

Application caches can also become obsolete. If an application's manifest file is removed from the server, the browser removes all application caches that use that manifest, and sends an "obsoleted" event to the applicationCache object. This sets the application cache's state to OBSOLETE.

The cache manifest file

Referencing a cache manifest file

The manifest attribute in a web application can specify either the relative path of a cache manifest file or an absolute URL. (Absolute URLs must be from the same origin as the application). A cache manifest file can have any file extension, but it must be served with the MIME type text/cache-manifest.

Note: On Apache servers, the MIME type for manifest (.appcache) files can be set by adding AddType text/cache-manifest .appcache to a .htaccess file within either the root directory, or the same directory as the application.

Entries in a cache manifest file

The cache manifest file is a simple text file that lists the resources the browser should cache for offline access. Resources are identified by URI. Entries listed in the cache manifest must have the same scheme, host, and port as the manifest. 

Example 1: a simple cache manifest file

The following is a simple cache manifest file, example.appcache, for an imaginary web site at www.example.com.

CACHE MANIFEST
# v1 - 2011-08-13
# This is a comment.
http://www.example.com/index.html
http://www.example.com/header.png
http://www.example.com/blah/blah

A cache manifest file can include three sections (CACHENETWORK, and FALLBACK, discussed below). In the example above, there is no section header, so all data lines are assumed to be in the explicit (CACHE) section, meaning that the browser should cache all the listed resources in the application cache. Resources can be specified using either absolute or relative URLs (e.g., index.html).

The "v1" comment in the example above is there for a good reason. Browsers only update an application cache when the manifest file changes, byte for byte. If you change a cached resource (for example, you update the header.png image with new content), you must also change the content of the manifest file in order to let browsers know that they need to refresh the cache. You can make any change you want to the manifest file, but revising a version number is the recommended best practice.

Important: Do not specify the manifest itself in the cache manifest file, otherwise it will be nearly impossible to inform the browser a new manifest is available.

Sections in a cache manifest file: CACHENETWORK, and FALLBACK

A manifest can have three distinct sections: CACHENETWORK, and FALLBACK.

CACHE:
This is the default section for entries in a cache manifest file. Files listed under the CACHE: section header (or immediately after the CACHE MANIFEST line) are explicitly cached after they're downloaded for the first time.
NETWORK:
Files listed under the NETWORK: section header in the cache manifest file are white-listed resources that require a connection to the server. All requests to such resources bypass the cache, even if the user is offline. Wildcards may be used.
FALLBACK:
The FALLBACK: section specifies fallback pages the browser should use if a resource is inaccessible. Each entry in this section lists two URIs—the first is the resource, the second is the fallback. Both URIs must be relative and from the same origin as the manifest file. Wildcards may be used.

The CACHENETWORK, and FALLBACK sections can be listed in any order in a cache manifest file, and each section can appear more than once in a single manifest.

Example 2: a more complete cache manifest file

The following is a more complete cache manifest file for the imaginary web site at www.example.com:

CACHE MANIFEST
# v1 2011-08-14
# This is another comment
index.html
cache.html
style.css
image1.png

# Use from network if available
NETWORK:
network.html

# Fallback content
FALLBACK:
/ fallback.html

This example uses NETWORK and FALLBACK sections to specify that the network.html page must always be retrieved from the network, and that the fallback.html page should be served as a fallback resource (e.g., in case a connection to the server cannot be established).

Structure of a cache manifest file

Cache manifest files must be served with the text/cache-manifest MIME type. All resources served using this MIME type must follow the syntax for an application cache manifest, as defined in this section.

Cache manifests are UTF-8 format text files, and may optionally include a BOM character. Newlines may be represented by line feed (U+000A), carriage return (U+000D), or carriage return and line feed both.

The first line of the cache manifest must consist of the string CACHE MANIFEST (with a single U+0020 space between the two words), followed by zero or more space or tab characters. Any other text on the line is ignored.

The remainder of the cache manifest must be comprised of zero or more of the following lines:

Blank line
You may use blank lines comprised of zero or more space and tab characters.
Comment
Comments consist of zero or more tabs or spaces followed by a single # character, followed by zero or more characters of comment text. Comments may only be used on their own lines, and cannot be appended to other lines. This means that you cannot specify fragment identifiers.
Section header
Section headers specify which section of the cache manifest is being manipulated. There are three possible section headers:
Section header Description
CACHE: Switches to the explicit section of the cache manifest (this is the default section).
NETWORK: Switches to the online whitelist section of the cache manifest.
FALLBACK: Switches to the fallback section of the cache manifest.
The section header line may include whitespaces, but must include the colon (:) in the section name.
Section data
The format for lines of data varies from section to section. In the explicit (CACHE:) section, each line is a valid URI or IRI reference to a resource to cache (no wildcard characters are allowed in this sections). Whitespace is allowed before and after the URI or IRI on each line. In the Fallback section each line is a valid URI or IRI reference to a resource, followed by a fallback resource that is to be served up when a connection with the server cannot be made. In the network section, each line is a valid URI or IRI reference to a resource to fetch from the network (the wildcard character * is allowed in this section).
Note: Relative URIs are relative to the cache manifest's URI, not to the URI of the document referencing the manifest.

Cache manifest files can switch from section to section at will (each section header can be used more than once), and sections are allowed to be empty.

Resources in an application cache

An application cache always includes at least one resource, identified by URI. All resources fit into one of the following categories:

Master entries
These are resources added to the cache because a browsing context visited by the user included a document that indicated that it was in this cache using its manifest attribute.
Explicit entries
These are resources explicitly listed in the application's cache manifest file.
Network entries
These are resources listed in the application's cache manifest files as network entries.
Fallback entries
These are resources listed in the application's cache manifest files as fallback entries.
Note: Resources can be tagged with multiple categories, and can therefore be categorized as multiple entries.  For example, an entry can be both an explicit entry and a fallback entry.

Resource categories are described in greater detail below.

Master entries

Master entries are any HTML files that include a {{ htmlattrxref("manifest","html") }} attribute in their {{ HTMLElement("html") }} element.  For example, let's say we have the HTML file http://www.example.com/entry.html, which looks like this:

<html manifest="example.appcache">
  <h1>Application Cache Example</h1>
</html>

If entry.html is not listed in the example.appcache cache manifest file, visiting the entry.html page causes entry.html to be added to the application cache as a master entry.

Explicit entries

Explicit entries are resources that are explicitly listed in the CACHE section of a cache manifest file.

Network entries

The NETWORK section of a cache manifest file specifies resources for which a web application requires online access. Network entries in an application cache are essentially an "online whitelist"—URIs specified in the NETWORK section are loaded from the server instead of the cache. This lets the browser's security model protect the user from potential security breaches by limiting access to approved resources.

As an example, you can use network entries to load and execute scripts and other code from the server instead of the cache:

CACHE MANIFEST
NETWORK:
/api

The cache manifest section listed above ensures that requests to load resources contained in the http://www.example.com/api/ subtree always go to the network without attempting to access the cache.

Note: Simply omitting master entries (files that have the manifest attribute set in the html element) from the manifest file would not have the same result, because master entries will be added—and subsequently served from—the application cache. 

Fallback entries

Fallback entries are used when an attempt to load a resource fails.  For example, let's say the cache manifest file http://www.example.com/example.appcache includes the following content:

CACHE MANIFEST
FALLBACK:
example/bar/ example.html

Any request to http://www.example.com/example/bar/ or any of its subdirectories and their content cause the browser to issue a network request to attempt to load the requested resource.  If the attempt fails, due to either a network failure or a server error of some kind, the browser loads the file example.html instead.

Cache states

Each application cache has a state, which indicates the current condition of the cache.  Caches that share the same manifest URI share the same cache state, which can be one of the following:

UNCACHED
A special value that indicates that an application cache object is not fully initialized.
IDLE
The application cache is not currently in the process of being updated.
CHECKING
The manifest is being fetched and checked for updates.
DOWNLOADING
Resources are being downloaded to be added to the cache, due to a changed resource manifest.
UPDATEREADY
There is a new version of the application cache available.  There is a corresponding updateready event, which is fired instead of the cached event when a new update has been downloaded but not yet activated using the swapCache() method.
OBSOLETE
The application cache group is now obsolete.

Testing for updates to the cache manifest

You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test window.applicationCache.status.

function onUpdateReady() {
  alert('found new version!');
}
window.applicationCache.addEventListener('updateready', onUpdateReady);
if(window.applicationCache.status === window.applicationCache.UPDATEREADY) {
  onUpdateReady();
}

 To manually start testing for a new manifest file, you can use window.applicationCache.update().

Gotchas

  • Never access cached files by using traditional GET parameters (like other-cached-page.html?parameterName=value). This will make the browser bypass the cache and attempt to get it from network. To link to cached resources that have parameters parsed in JavaScript use parameters in the hash part of the link, such as other-cached-page.html#whatever?parameterName=value.
  • When applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. You must update the cache manifest file itself before the browser retrieves and uses the updated files. You can do this programmatically using window.applicationCache.swapCache(), though resources that have already been loaded will not be affected. To make sure that resources are loaded from a new version of the application cache, refreshing the page is ideal.
  • It's a good idea to set expires headers on your web server for *.appcache files to expire immediately. This avoids the risk of caching manifest files. For example, in Apache you can specify such a configuration as follows:
    ExpiresByType text/cache-manifest "access plus 0 seconds"

Browser Compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 4.0 3.5 10.0 10.6 4.0
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 2.1 {{ CompatVersionUnknown() }} {{ CompatNo() }} 11.0 3.2

Note: Versions of Firefox prior to 3.5 ignore the NETWORK and FALLBACK sections of the cache manifest file.

See also

{{ HTML5ArticleTOC() }}

 

Fuente de la revisión

<h2 id="Introduction">Introducción</h2>
<p><a href="https://developer.mozilla.org/en-US/docs/HTML/HTML5" title="/en-US/docs/HTML/HTML5">HTML5</a> proporciona un mecanismo de <em>caché de aplicación</em> que permite que las aplicaciones basadas en la web se ejecuten sin conexión. Los desarrolladores pueden usar la interface de <strong>Caché de apliaciones</strong> (<em>AppCache</em>) para especificar los recursos que el navegador debería guardar en caché y tener disponibles para los usuarios cuando no estén conectados. Las aplicaciones que están en caché se cargan y funcionan correctamente aunque los usuarios hagan clic en el botón recargar cuando no están conectados.</p>
<p>Usar el caché de aplicaciones le da a la aplicación los siguientes beneficios:</p>
<ul>
  <li>Navegación sin conexión: los usuarios pueden navegar un sitio aún cuando no estén conectados.</li>
  <li>Velocidad: los recursos en caché son locales, y por lo tanto, se cargan más rápido.</li>
  <li>Carga al servidor reducida: el navegador solamente descarga desde el servidor recursos que han cambiado..</li>
</ul>
<h3 id=".C2.BFC.C3.B3mo_funciona_la_cach.C3.A9_de_aplicaci.C3.B3n.3F">¿Cómo funciona el caché de aplicaciones?</h3>
<h3 id="Enabling_the_application_cache">Habilitando caché de apliaciones</h3>
<p>Para habilitar el caché de apliaciones, debe incluir el atributo {{htmlattrxref("manifest", "html")}} en el elemento {{HTMLElement("html")}} en las páginas de sus aplicaciones, como se muestra en el siguiente ejemplo:</p>
<div>
  <pre class="brush: html">
<span class="brush: html">&lt;html manifest="ejemplo.appcache"&gt; </span>
  ...
&lt;/html&gt;
</pre>
</div>
<p>El atributo manifest referencua un archivo <strong>manifiesto de cache</strong>, que es un archivo de texto que lista los recursos (archivos) que el navegador deberá guardar en caché para la aplicación.</p>
<p>Debería incluir el atributo <code>manifest</code> en cada página de la aplicación que quiera guardar en caché. El navegador no guardará páginas que no contengan el atributo&nbsp; <code>manifest</code>, a menos que esas páginas estén específicamente listadas en el archivo de manifiesto en sí mismo. No es necesario listar todas las páginas que se quieran guardar en caché en el archivo de manfifesto, el navegador implícitamente agrega cada página que el usuario visite y tenga el atributo <code>manifest</code> establecido para caché de aplicación.</p>
<p>Algunos navegadores (ej. Firefox) muestran una notificación la primera vez que un usuario carga una aplicación que usa caché de aplicaciones La barra de notificaciones muestra un mensaje parecido a :</p>
<p style="margin-left: 40px; ">Este sitio web (<code>www.ejemplo.com</code>) está pidiendo guardar datos en su equpo para suar sin conexión. [Permitir] [Nunca para este sitio] [No por ahora]</p>
<p>El término "offline(-enabled) applications" a veces se refiere específicamente a aplicaciones a las que el usuario ha permitido que usen capacidades sin conexión.</p>
<h3 id="Loading_documents">Cargando documentos</h3>
<div>
  <p>Es uso de caché de aplicaciones modifica el proceso normal de la carga de un documento:</p>
  <ul>
    <li>Si existe caché de aplicaciones, el navegador carga el documento y sus recursos asociados directamente desde ahí, sin acceder a la red. Esto acelera el tiempo de carga del documento.</li>
    <li>El navegador entonces verifica si hubo actualizaciones al manifiesto de caché en el servidor.</li>
    <li>Si el manifiesto de caché fue actualizado, el navegador descarga la nueva versión del archivo y de los recursos listados en él. Esto se realiza en segundo plano y no afecta el rendimiento de forma significativa.</li>
  </ul>
  <p>El proceso para cargar documentos y actualizar el caché de aplicaciones está especificado con gran detalle aquí debajo:</p>
</div>
<ol>
  <li>Cuando el navegador visita un documento que incluye el atributo <code>manifest</code>, si no existe caché de apliaciones, el navegador carga el documento y baja todas las entradas listadas en el archivo de manifiesto, creando la primera versón de caché de aplicaciones.&nbsp;</li>
  <li>Posteriores visitas a ese documento causan que el navegador cargue el documento y otros archivos especificados en el manifiesto desde el caché de aplicaciones (no desde el servidor).&nbsp; Además, el navegador envía un evento <code>checking</code> al objeto <code><a href="https://developer.mozilla.org/en/DOM/window.applicationCache" title="en/DOM/window.applicationCache">window.applicationCache</a></code> y descarga el archivo de manifiesto, siguiendo las reglas de caché HTTP apropiadas.</li>
  <li>Si la copia del manifiesto actualmente en caché está actualizada, el navegador envía un evento <code>noupdate</code> al objeto <code>applicationCache</code> y el proceso de actualización está completo. Hay que tener en cuenta que si se cambia en el servidor cualquier recurso en caché, se deberá cambiar también el archivo de manifiesto, para que el navegador sepa que deberá descargar los recursos nuevamente.</li>
  <li>Si el archivo de manifiesto <em>ha</em> cambiado, todos los archivos listados en el manifiesto—así como los que se agregaron al caché llamando <code><a href="https://developer.mozilla.org/en/nsIDOMOfflineResourceList#add.28.29" title="en/nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a></code>—se descargarán en un caché temporario, siguiendo las reglas de caché&nbsp; HTTP apropiadas. Para cada archivo descargado en este caché temporario, el navegador envía un evento <code>progress</code> al objeto <code>applicationCache</code>. Si ocurre cualquier error, el navegador envía un evento <code>error</code> y la actualización se detiene.</li>
  <li>Una vez que todos los archivos han sido recuperados exitosamente, son movidos al caché sin conexión real automáticamente y un evento <code>cached</code> es enviado al objeto <code>applicationCache</code>. Como el documento ya ha sido cargado en el navegador desde caché, la actualización no se mostrará hasta que el documento sea recargado (ya sea manualmente o por programa).</li>
</ol>
<h2 id="Storage_location_and_clearing_the_offline_cache">Ubicación del almacenamiento y limpiando el caché sin conexión</h2>
<p>En Chrome se puede limpiar el caché sin conexión seleccionando "Clear browsing data..." en las preferencias o visitando <a class="external" title="chrome://appcache-internals/">chrome://appcache-internals/</a>. Safari tiene una configuración similar"Vaciar cache" en sus preferencias, pero se requiere el reinicio del navegador.</p>
<p>En Firefox, el caché sin conexión se guarda en un lugar separado del perfil de Firefox profile—cerca del caché de disco regular:</p>
<ul>
  <li>Windows Vista/7: <code>C:\Users\&lt;username&gt;\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\&lt;salt&gt;.&lt;profile name&gt;\OfflineCache</code></li>
  <li>Mac/Linux:&nbsp;<code>/Users/&lt;username&gt;/Library/Caches/Firefox/Profiles/&lt;salt&gt;.&lt;profile name&gt;/OfflineCache</code></li>
</ul>
<p>In Firefox the current status of the offline cache can be inspected on the <code>about:cache</code> page (under the "Offline cache device" heading). The offline cache can be cleared for each site separately using the "Remove..." button in Tools -&gt; Options -&gt; Advanced -&gt; Network -&gt; Offline data.</p>
<p>Prior to Firefox 11, neither Tools -&gt; Clear Recent History nor Tools -&gt; Options -&gt; Advanced -&gt; Network -&gt; Offline data -&gt; Clear Now cleared the offline cache. This has been fixed.</p>
<p>See also <a href="https://developer.mozilla.org/en/DOM/Storage#Storage_location_and_clearing_the_data" title="en/DOM/Storage#Storage location and clearing the data">clearing the DOM&nbsp;Storage data</a>.</p>
<div>
  <p>Application caches can also become obsolete. If an application's manifest file is removed from the server, the browser removes all application caches that use that manifest, and sends an "obsoleted" event to the&nbsp;<code>applicationCache</code>&nbsp;object. This sets the application cache's state to&nbsp;<code>OBSOLETE</code>.</p>
</div>
<h2 id="The_cache_manifest_file">The cache manifest file</h2>
<h3 id="Referencing_a.C2.A0cache_manifest_file">Referencing a&nbsp;cache manifest file</h3>
<p>The&nbsp;<code>manifest</code>&nbsp;attribute in a web application can specify either the relative path of a cache manifest file or&nbsp;an absolute URL. (Absolute URLs must be from the same origin as the application). A cache manifest file can have any file extension, but it must be served with the MIME type&nbsp;<code>text/cache-manifest</code>.</p>
<div class="note">
  <strong>Note: </strong>On Apache servers, the MIME type for manifest (.appcache) files can be set by adding <code>AddType text/cache-manifest .appcache</code> to a .htaccess file within either the root directory, or the same directory as the application.</div>
<h3 id="Entries_in_a.C2.A0cache_manifest_file">Entries in a&nbsp;cache manifest file</h3>
<p>The cache manifest file is a simple text file that lists the resources the browser should cache for offline access. Resources are identified by URI. Entries listed in the cache manifest&nbsp;must have the same scheme, host, and port as the manifest.&nbsp;</p>
<h3 id="Example_1.3A_a_simple_cache_manifest_file">Example 1: a simple cache manifest file</h3>
<div>
  <p>The following is a simple cache manifest file,&nbsp;<code>example.appcache</code>, for an imaginary web site at&nbsp;<span class="nowiki">www.example.com</span>.</p>
  <pre class="eval">
CACHE MANIFEST
# v1 - 2011-08-13
# This is a comment.
<span class="nowiki">http://www.example.com/index.html</span>
<span class="nowiki">http://www.example.com/header.png</span>
<span class="nowiki">http://www.example.com/blah/blah</span>
</pre>
  <p>A cache manifest file can include three sections (<code>CACHE</code>,&nbsp;<code>NETWORK</code>, and&nbsp;<code>FALLBACK</code>, discussed below). In the example above, there is no section header, so all data lines are assumed to be in the explicit (<code>CACHE</code>) section, meaning that the browser should cache all the listed resources in the application cache. Resources can be specified using either absolute or relative URLs (e.g.,&nbsp;<code>index.html</code>).</p>
  <p>The "v1" comment in the example above is there for a good reason. Browsers only update an application cache when the manifest file changes, byte for byte. If you change a cached resource (for example, you update the&nbsp;<code>header.png</code>&nbsp;image with new content), you must also change the content of the manifest file in order to let browsers know that they need to refresh the cache. You can make any change you want to the manifest file, but revising a version number is the recommended best practice.</p>
  <div class="warning">
    <strong>Important:</strong>&nbsp;Do not specify the manifest itself in the cache manifest file, otherwise it will be nearly impossible to inform the browser a new manifest is available.</div>
  <h3 id="Sections_in_a_cache_manifest_file.3A.C2.A0CACHE.2C.C2.A0NETWORK.2C_and.C2.A0FALLBACK">Sections in a cache manifest file:&nbsp;<code>CACHE</code>,&nbsp;<code>NETWORK</code>, and&nbsp;<code>FALLBACK</code></h3>
  <p>A manifest can have three distinct sections:&nbsp;<code>CACHE</code>,&nbsp;<code>NETWORK</code>, and&nbsp;<code>FALLBACK</code>.</p>
  <dl>
    <dt>
      <code>CACHE:</code></dt>
    <dd>
      This is the default section for entries in a cache manifest file. Files listed under the&nbsp;<code>CACHE:</code>&nbsp;section header (or immediately after the&nbsp;<code>CACHE MANIFEST</code>&nbsp;line) are explicitly cached after they're downloaded for the first time.</dd>
    <dt>
      <code>NETWORK:</code></dt>
    <dd>
      Files listed under the&nbsp;<code>NETWORK:</code>&nbsp;section header in the cache manifest file are white-listed resources that require a connection to the server. All requests to such resources bypass the cache, even if the user is offline. Wildcards may be used.</dd>
    <dt>
      <code>FALLBACK:</code></dt>
    <dd>
      The&nbsp;<code>FALLBACK:</code>&nbsp;section specifies fallback pages the browser should use if a resource is inaccessible. Each entry in this section lists two URIs—the first is the resource, the second is the fallback. Both URIs must be relative and from the same origin as the manifest file. Wildcards may be used.</dd>
  </dl>
  <p>The&nbsp;<code>CACHE</code>,&nbsp;<code>NETWORK</code>, and&nbsp;<code>FALLBACK&nbsp;</code>sections can be listed in any order in a cache manifest file, and each section can appear more than once in a single manifest.</p>
  <h3 id="Example_2.3A_a_more_complete_cache_manifest_file">Example 2: a more complete cache manifest file</h3>
  <p>The following is a more complete cache manifest file for the imaginary web site at&nbsp;<span class="nowiki">www.example.com</span>:</p>
  <pre class="eval">
CACHE MANIFEST
# v1 2011-08-14
# This is another comment
index.html
cache.html
style.css
image1.png

# Use from network if available
NETWORK:
network.html

# Fallback content
FALLBACK:
/ fallback.html
</pre>
  <p>This example uses&nbsp;<code>NETWORK</code>&nbsp;and&nbsp;<code>FALLBACK</code>&nbsp;sections to specify that the&nbsp;<code>network.html</code>&nbsp;page must always be retrieved from the network, and that the&nbsp;<code>fallback.html</code>&nbsp;page should be served as a fallback resource (e.g., in case a connection to the server cannot be established).</p>
  <h3 id="Structure_of_a_cache_manifest_file">Structure of a cache manifest file</h3>
  <p>Cache manifest files must be served with the&nbsp;<code>text/cache-manifest</code>&nbsp;MIME type. All resources served using this MIME type must follow the syntax for an application cache manifest, as defined in this section.</p>
  <p>Cache manifests are UTF-8 format text files, and may optionally include a BOM character. Newlines may be represented by line feed (<code>U+000A</code>), carriage return (<code>U+000D</code>), or carriage return and line feed both.</p>
  <p>The first line of the cache manifest must consist of the string&nbsp;<code>CACHE MANIFEST</code>&nbsp;(with a single&nbsp;<code>U+0020</code>&nbsp;space between the two words), followed by zero or more space or tab characters. Any other text on the line is ignored.</p>
  <p>The remainder of the cache manifest must be comprised of zero or more of the following lines:</p>
  <dl>
    <dt>
      Blank line</dt>
    <dd>
      You may use blank lines comprised of zero or more space and tab characters.</dd>
    <dt>
      Comment</dt>
    <dd>
      Comments consist of zero or more tabs or spaces followed by a single&nbsp;<code>#</code>&nbsp;character, followed by zero or more characters of comment text. Comments may only be used on their own lines, and cannot be appended to other lines. This means that you cannot specify fragment identifiers.</dd>
    <dt>
      Section header</dt>
    <dd>
      Section headers specify which section of the cache manifest is being manipulated. There are three possible section headers:</dd>
  </dl>
  <blockquote>
    <table class="standard-table">
      <tbody>
        <tr>
          <th>Section header</th>
          <th>Description</th>
        </tr>
        <tr>
          <td><code>CACHE:</code></td>
          <td>Switches to the explicit section of the cache manifest (this is the default section).</td>
        </tr>
        <tr>
          <td><code>NETWORK:</code></td>
          <td>Switches to the online whitelist section of the cache manifest.</td>
        </tr>
        <tr>
          <td><code>FALLBACK:</code></td>
          <td>Switches to the fallback section of the cache manifest.</td>
        </tr>
      </tbody>
    </table>
  </blockquote>
  <dl>
    <dd>
      The section header line may include whitespaces, but must include the colon (<code>:</code>) in the section name.</dd>
    <dt>
      Section data</dt>
    <dd>
      The format for lines of data varies from section to section. In the explicit (<code>CACHE:</code>) section, each line is a valid URI or IRI reference to a resource to cache (no wildcard characters are allowed in this sections). Whitespace is allowed before and after the URI or IRI on each line. In the Fallback section each line is a valid URI or IRI reference to a resource, followed by a fallback resource that is to be served up when a connection with the server cannot be made. In the network section, each line is a valid URI or IRI reference to a resource to fetch from the network (the wildcard character * is allowed in this section).<br />
      <div class="note">
        <strong>Note:&nbsp;</strong>Relative URIs are relative to the cache manifest's URI, not to the URI of the document referencing the manifest.</div>
    </dd>
  </dl>
  <p>Cache manifest files can switch from section to section at will (each section header can be used more than once), and sections are allowed to be empty.</p>
  <h2 id="Resources_in_an_application_cache">Resources in an application cache</h2>
  <p>An application cache always includes at least one resource, identified by URI. All resources fit into one of the following categories:</p>
  <dl>
    <dt>
      Master entries</dt>
    <dd>
      These are resources added to the cache because a browsing context visited by the user included a document that indicated that it was in this cache using its&nbsp;<code>manifest</code>&nbsp;attribute.</dd>
    <dt>
      Explicit entries</dt>
    <dd>
      These are resources explicitly listed in the application's cache manifest file.</dd>
    <dt>
      Network entries</dt>
    <dd>
      These are resources listed in the application's cache manifest files as network entries.</dd>
    <dt>
      Fallback entries</dt>
    <dd>
      These are resources listed in the application's cache manifest files as fallback entries.</dd>
  </dl>
  <div class="note">
    <strong>Note:</strong>&nbsp;Resources can be tagged with multiple categories, and can therefore be categorized as multiple entries.&nbsp; For example, an entry can be both an explicit entry and a fallback entry.</div>
  <p>Resource categories are described in greater detail below.</p>
  <h3 id="Master_entries">Master entries</h3>
  <p>Master entries are any HTML&nbsp;files that include a {{ htmlattrxref("manifest","html") }} attribute in their {{ HTMLElement("html") }} element.&nbsp; For example, let's say we have the HTML&nbsp;file&nbsp;<code><a class="linkification-ext external" href="http://www.foo.bar/entry.html" title="Linkification: http://www.foo.bar/entry.html">http://www.example.com/entry.html</a></code>, which looks like this:</p>
  <pre class="brush: html">
&lt;html manifest="example.appcache"&gt;
  &lt;h1&gt;Application Cache Example&lt;/h1&gt;
&lt;/html&gt;
</pre>
  <p>If&nbsp;<code>entry.html</code>&nbsp;is not listed in the&nbsp;<code>example.appcache</code>&nbsp;cache manifest file, visiting the&nbsp;<code>entry.html</code>&nbsp;page causes&nbsp;<code>entry.html</code>&nbsp;to be added to the application cache as a master entry.</p>
  <h3 id="Explicit_entries">Explicit entries</h3>
  <p>Explicit entries are resources that are explicitly listed in the <code>CACHE </code>section of a cache manifest file.</p>
  <h3 id="Network_entries">Network entries</h3>
  <p>The&nbsp;<code>NETWORK</code>&nbsp;section of a cache manifest file specifies resources for which a web application requires online access. Network entries in an application cache are essentially an "online whitelist"—URIs specified in the&nbsp;<code>NETWORK</code>&nbsp;section are loaded from the server instead of the cache. This lets the browser's security model protect the user from potential security breaches by limiting access to approved resources.</p>
  <p>As an example, you can use network entries to load and execute scripts and other code from the server instead of the cache:</p>
  <pre>
CACHE MANIFEST
NETWORK:
/api
</pre>
  <p>The cache manifest section listed above ensures that requests to load resources contained in the&nbsp;<code><a class="external" href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code>&nbsp;subtree always go to the network without attempting to access the cache.</p>
  <div class="note">
    <strong>Note</strong>:&nbsp;Simply omitting master entries (files that have the&nbsp;<code>manifest</code>&nbsp;attribute set in the&nbsp;<code>html</code>&nbsp;element) from the manifest file would not have the same result, because master entries will be added—and subsequently served from—the application cache.&nbsp;</div>
  <h3 id="Fallback_entries">Fallback entries</h3>
  <p>Fallback entries are used when an attempt to load a resource fails.&nbsp; For example, let's say the cache manifest file&nbsp;<code><a class="external" href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code>&nbsp;includes the following content:</p>
  <pre>
CACHE MANIFEST
FALLBACK:
example/bar/ example.html
</pre>
  <p>Any request to&nbsp;<code><a class="external" href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code>&nbsp;or any of its subdirectories and their content cause the browser to issue a network request to attempt to load the requested resource.&nbsp; If the attempt fails, due to either a network failure or a server error of some kind, the browser loads the file&nbsp;<code>example.html</code>&nbsp;instead.</p>
  <h2 id="Cache_states">Cache states</h2>
  <p>Each application cache has a&nbsp;<strong>state</strong>, which indicates the current condition of the cache.&nbsp; Caches that share the same manifest URI share the same cache state, which can be one of the following:</p>
  <dl>
    <dt>
      <code>UNCACHED</code></dt>
    <dd>
      A special value that indicates that an application cache object is not fully initialized.</dd>
    <dt>
      <code>IDLE</code></dt>
    <dd>
      The application cache is not currently in the process of being updated.</dd>
    <dt>
      <code>CHECKING</code></dt>
    <dd>
      The manifest is being fetched and checked for updates.</dd>
    <dt>
      <code>DOWNLOADING</code></dt>
    <dd>
      Resources are being downloaded to be added to the cache, due to a changed resource manifest.</dd>
    <dt>
      <code>UPDATEREADY</code></dt>
    <dd>
      There is a new version of the application cache available.&nbsp; There is a corresponding&nbsp;<code>updateready</code>&nbsp;event, which is fired instead of the&nbsp;<code>cached</code>&nbsp;event when a new update has been downloaded but not yet activated using the&nbsp;<code>swapCache()</code>&nbsp;method.</dd>
    <dt>
      <code>OBSOLETE</code></dt>
    <dd>
      The application cache group is now obsolete.</dd>
  </dl>
  <h2 id="Testing_for_updates_to_the_cache_manifest">Testing for updates to the cache manifest</h2>
  <p>You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test&nbsp;<code>window.applicationCache.status</code>.</p>
  <pre class="brush: js">
function onUpdateReady()&nbsp;{
&nbsp;&nbsp;alert('found new version!');
}
window.applicationCache.addEventListener('updateready', onUpdateReady);
if(window.applicationCache.status === window.applicationCache.UPDATEREADY) {
&nbsp;&nbsp;onUpdateReady();
}</pre>
  <p>&nbsp;To manually start testing for a new manifest file, you can use&nbsp;<code>window.applicationCache.update()</code>.</p>
  <h2 id="Gotchas">Gotchas</h2>
  <ul>
    <li>Never access cached files by using traditional GET parameters (like <code>other-cached-page.html?parameterName=value</code>). This will make the browser bypass the cache and attempt to get it from network. To link to cached resources that have parameters parsed in JavaScript use parameters in the hash part of the link, such as <code>other-cached-page.html#whatever?parameterName=value</code>.</li>
    <li>When applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. You must update the cache manifest file itself before the browser retrieves and uses the updated files. You can do this programmatically using&nbsp;<code>window.applicationCache.swapCache()</code>, though resources that have already been loaded will not be affected. To make sure that resources are loaded from a new version of the application cache, refreshing the page is ideal.</li>
    <li>It's a good idea to set expires headers on your web server for&nbsp;<code>*.appcache</code>&nbsp;files to expire immediately. This avoids the risk of caching manifest files. For example, in Apache you can specify such a configuration as follows:<br />
      <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li>
  </ul>
  <h2 id="Browser_Compatibility">Browser Compatibility</h2>
  <p>{{ CompatibilityTable() }}</p>
  <div id="compat-desktop">
    <table class="compat-table">
      <tbody>
        <tr>
          <th>Feature</th>
          <th>Chrome</th>
          <th>Firefox (Gecko)</th>
          <th>Internet Explorer</th>
          <th>Opera</th>
          <th>Safari</th>
        </tr>
        <tr>
          <td>Basic support</td>
          <td>4.0</td>
          <td>3.5</td>
          <td>10.0</td>
          <td>10.6</td>
          <td>4.0</td>
        </tr>
      </tbody>
    </table>
  </div>
  <div id="compat-mobile">
    <table class="compat-table">
      <tbody>
        <tr>
          <th>Feature</th>
          <th>Android</th>
          <th>Firefox Mobile (Gecko)</th>
          <th>IE Mobile</th>
          <th>Opera Mobile</th>
          <th>Safari Mobile</th>
        </tr>
        <tr>
          <td>Basic support</td>
          <td>2.1</td>
          <td>{{ CompatVersionUnknown() }}</td>
          <td>{{ CompatNo() }}</td>
          <td>11.0</td>
          <td>3.2</td>
        </tr>
      </tbody>
    </table>
  </div>
  <p>Note: Versions of Firefox prior to 3.5 ignore the&nbsp;<code>NETWORK&nbsp;</code>and&nbsp;<code>FALLBACK&nbsp;</code>sections of the cache manifest file.</p>
  <h2 id="See_also">See also</h2>
  <ul>
    <li><a class="external" href="http://www.html5rocks.com/en/tutorials/appcache/beginner/" title="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li>
    <li><a class="external" href="http://appcachefacts.info/" title="http://appcachefacts.info/">appcachefacts.info</a>&nbsp;- detailed information on AppCache idiosyncrasies</li>
    <li><a class="external" href="http://hacks.mozilla.org/2010/01/offline-web-applications/" title="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a>&nbsp;at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li>
    <li><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li>
    <li><a class="external" href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage" title="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li>
    <li>{{ interface("nsIApplicationCache") }}</li>
    <li>{{ interface("nsIApplicationCacheNamespace") }}</li>
    <li>{{ interface("nsIApplicationCacheContainer") }}</li>
    <li>{{ interface("nsIApplicationCacheChannel") }}</li>
    <li>{{ interface("nsIApplicationCacheService") }}</li>
    <li>{{ interface("nsIDOMOfflineResourceList") }}</li>
    <li><a class="external" href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a>&nbsp;(IBM developerWorks)</li>
  </ul>
  <p>{{ HTML5ArticleTOC() }}</p>
</div>
<p>&nbsp;</p>
Revertir a esta revisión