From 25debec66a35fc20db84bf5aca690489b5bec306 Mon Sep 17 00:00:00 2001 From: julieng Date: Sun, 11 Apr 2021 16:03:26 +0200 Subject: Archiving HTML - Using the Application cache --- .../html/using_the_application_cache/index.html | 375 ------------------- .../html/using_the_application_cache/index.html | 383 -------------------- .../html/using_the_application_cache/index.html | 339 ----------------- .../html/using_the_application_cache/index.html | 384 -------------------- .../html/using_the_application_cache/index.html | 350 ------------------ .../html/using_the_application_cache/index.html | 338 ----------------- .../html/using_the_application_cache/index.html | 392 -------------------- .../html/using_the_application_cache/index.html | 343 ------------------ .../html/using_the_application_cache/index.html | 329 ----------------- .../html/using_the_application_cache/index.html | 401 --------------------- .../html/using_the_application_cache/index.html | 391 -------------------- 11 files changed, 4025 deletions(-) delete mode 100644 files/de/web/html/using_the_application_cache/index.html delete mode 100644 files/es/web/html/using_the_application_cache/index.html delete mode 100644 files/fr/web/html/using_the_application_cache/index.html delete mode 100644 files/it/web/html/using_the_application_cache/index.html delete mode 100644 files/ja/web/html/using_the_application_cache/index.html delete mode 100644 files/ko/web/html/using_the_application_cache/index.html delete mode 100644 files/pt-br/web/html/using_the_application_cache/index.html delete mode 100644 files/pt-pt/web/html/using_the_application_cache/index.html delete mode 100644 files/ru/web/html/using_the_application_cache/index.html delete mode 100644 files/zh-cn/web/html/using_the_application_cache/index.html delete mode 100644 files/zh-tw/web/html/using_the_application_cache/index.html (limited to 'files') diff --git a/files/de/web/html/using_the_application_cache/index.html b/files/de/web/html/using_the_application_cache/index.html deleted file mode 100644 index 1afea42d7d..0000000000 --- a/files/de/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,375 +0,0 @@ ---- -title: Benutzung des Application Cache -slug: Web/HTML/Using_the_application_cache -translation_of: Web/HTML/Using_the_application_cache ---- -

Einführung

- -

HTML5 bietet einen Anwendungscaching-Mechanismus, welcher webbasierte Anwendungen offline nutzbar macht. Entwickler können das Application Cache (AppCache) - Interface nutzen, um Ressourcen, die der Browser cachen soll für die Offline-Nutzung verfügbar zu machen. Gecachte Anwendungen laden und arbeiten korrekt, auch wenn der User den "Neu laden" - Button des Browsers klickt.

- -

Die Nutzung des Application Cache ermöglicht einer Anwendung folgende Vorteile: 

- - - -

Wie der AppCache funktioniert

- -

Aktivieren des AppCaches

- -

Zum Aktivieren des ApplicationCaches für eine App muss das {{htmlattrxref("manifest", "html")}}-Attribute in das {{HTMLElement("html")}}-Element auf allen Seiten der App eingebunden werden, wie folgendes Beispiel zeigt:

- -
-
<html manifest="example.appcache">
-  ...
-</html>
-
-
- -

Das Manifest-Attribut verweist auf eine cache manifest-Datei, die als Textdatei alle Ressourcen (Dateien) auflistet, die der Browser innerhalb der App cachen soll.

- -

Sie sollten das manifest-Attribute auf jeder Seite Ihrer App einbinden, die zwischengespeichert werden soll. Der Browser speichert keine Seiten die nicht das manifest-Attribute besitzen, außer manche Seiten sind explizit in der manifest-Datei beschrieben. Sie müssen nicht alle Dateien einzeln in die manifest-Datei schreiben die gespeichert werden sollen, der Browser fügt jede Seite indirekt hinzu die der Benutzer besucht und die, die das manifest-Attribute enthalten.

- -

Manche Browser (z.B. Firefox) zeigen eine Benachrichtigung an, dass ein entsprechender App-Cache verwendet wird, wenn ein Benutzer die App das erste Mal besucht. Die Benachrichtigungsleiste zeigt dann in etwa folgendes an:

- -

Die Webseite (www.example.com) möchte gerne Daten zur Offline-Benutzung abspeichern. [Erlauben] [Nie für diese Seite] [Nicht jetzt]

- -

The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities.

- -

Loading documents

- -

The use of an application cache modifies the normal process of loading a document:

- - - -

The process for loading documents and updating the application cache is specified in greater detail below:

- -
    -
  1. When the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and then fetches all the entries listed in the manifest file, creating the first version of the application cache.
  2. -
  3. Subsequent visits to that document cause the browser to load the document and other assets specified in the manifest file from the application cache (not from the server). In addition, the browser also sends a checking event to the window.applicationCache object, and fetches the manifest file, following the appropriate HTTP caching rules.
  4. -
  5. If the currently-cached copy of the manifest is up-to-date, the browser sends a noupdate event to the applicationCache object, and the update process is complete. Note that if you change any cached resources on the server, you must also change the manifest file itself, so that the browser knows it needs to fetch all the resources again.
  6. -
  7. If the manifest file has changed, all the files listed in the manifest—as well as those added to the cache by calling applicationCache.add()—are fetched into a temporary cache, following the appropriate HTTP caching rules. For each file fetched into this temporary cache, the browser sends a progress event to the applicationCache object. If any errors occur, the browser sends an error event, and the update halts.
  8. -
  9. Once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a cached event is sent to the applicationCache object. Since the document has already been loaded into the browser from the cache, the updated document will not be rendered until the document is reloaded (either manually or programatically).
  10. -
- -

Storage location and clearing the offline cache

- -

In Chrome you can clear the offline cache by selecting "Clear browsing data..." in the preferences or by visiting chrome://appcache-internals/. Safari has a similar "Empty cache" setting in its preferences but a browser restart may also be required.

- -

In Firefox, the offline cache data is stored separately from the Firefox profile—next to the regular disk cache:

- - - -

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 "obsolete" 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 (CACHE, NETWORK, 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: CACHE, NETWORK, and FALLBACK

- -

A manifest can have three distinct sections: CACHE, NETWORK, 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 CACHE, NETWORK, 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 headerDescription
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

- - - -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support4.03.510.010.64.0
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatVersionUnknown}}{{CompatNo}}11.03.2
-
- -

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

- -

See also

- - - -
{{HTML5ArticleTOC}}
diff --git a/files/es/web/html/using_the_application_cache/index.html b/files/es/web/html/using_the_application_cache/index.html deleted file mode 100644 index 65a9554239..0000000000 --- a/files/es/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,383 +0,0 @@ ---- -title: Usar el caché de aplicaciones -slug: Web/HTML/Using_the_application_cache -tags: - - Firefox 3.5 - - HTML5 - - aplicaciones web sin conexión - - para_revisar -translation_of: Web/HTML/Using_the_application_cache -original_slug: Web/HTML/Recursos_offline_en_firefox ---- -

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 aplicaciones (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:

- - - -

¿Cómo funciona el caché de aplicaciones?

- -

Habilitando caché de aplicaciones

- -

Para habilitar el caché de aplicaciones, 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 referencia un archivo manifest de caché, 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 manifest 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 equipo para usar 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:

- - - -

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 aplicaciones, el navegador carga el documento y baja todas las entradas listadas en el archivo del manifest, creando la primera versón de caché de aplicaciones. 
  2. -
  3. Posteriores visitas a ese documento causan que el navegador cargue el documento y otros archivos especificados en el manifest 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 manifest, siguiendo las reglas de caché HTTP apropiadas.
  4. -
  5. Si la copia del manifest 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 manifest, para que el navegador sepa que deberá descargar los recursos nuevamente.
  6. -
  7. Si el archivo de manifest ha cambiado, todos los archivos listados en el manifest—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.
  8. -
  9. 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 re-cargado (ya sea manualmente o por programa).
  10. -
- -

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:

- - - -

En Firefox el estado actual del caché de aplicaciones puede ser inspeccionado en la página the about:cache (debajo del encabezado "Offline cache device"). El caché sin conexión pude limpiarse para cada sitio por separado usando el botón "Eliminar..." Herramientas -> Opciones -> Avanzadas -> Red -> Datos sin conexión.

- -

Antes de Firefox 11, ni Herramientas -> Limpiar historial reciente ni Herramientas -> Opciones -> Avanzadas -> Red -> Datos sin conexión -> Limpiar ahora borraban el caché sin conexión. Esto ha sido solucionado.

- -

Véase también limpiar los datos de almacenamiento de DOM.

- -
-

Los cachés de aplicaciones también pueden quedar obsoletos. Si el archivo de manifest de una aplicación es eliminado del servidor, el navegador elimina todo caché de la aplicación que use aquel manifest y envía un evento "obsoleted" al objeto applicationCache. Esto cambia el estado de caché de la aplicación a OBSOLETE.

-
- -

El archivo de manifest de caché

- -

Referenciando un archivo de manifest de caché

- -

El atributo manifest en una aplicación web puede especificar ya sea la ruta relativa de un archivo de manifest de caché o una URL absoluta (URLs absolutas deben estar en el mismo origen que la aplicación). Un archivo de manifest de caché puede tener cualquier extensión de archivo, pero debe ser enviada con el tipo MIME text/cache-manifest.

- -
Nota: En servidores Apache, el tipo MIME para los archivos de manifest (.appcache) puede establecerse agregando AddType text/cache-manifest .appcache a un archivo .htaccess dentro del directorio raíz o del mismo directorio que la aplicación.
- -

Entradas en el archivo de manifest de caché

- -

El archivo de manifest de caché es un archivo de texto simple que lista los recursos que el navegador debería guardar en caché para acceder sin conexión. Los recursos son identificados por URI. Las entradas listadas en el manifest de caché deben tener el mismo esquema, servidor y puerto que el manifest. 

- -

Ejemplo 1: un archivo de manifest de caché simple

- -
-

El siguiente es un archivo de manifest de caché simple, ejemplo.appcache, para un sitio web imaginario en www.ejemplo.com.

- -
CACHE MANIFEST
-# v1 - 2011-08-13
-# Esto es un comentario.
-http://www.ejemplo.com/index.html
-http://www.ejemplo.com/encabezado.png
-http://www.ejemplo.com/blah/blah
-
- -

Un archivo de manifest de caché puede incluir tres secciones (CACHENETWORK y FALLBACK, discutidas debajo). En el ejemplo mencionado, no hay encabezado de sección, así que todoas las líneas de datos se asumen como si estuvieran en la sección explícita (CACHE), lo que significa que el navegador deberá guardar en caché todos los recursos listados en el caché de aplicación. Los recursos pueden ser especificados como URLs absolutas o relativas (ej. index.html).

- -

El comentario "v1" en el ejemplo está ahí por una buena razón. Los navegadores solamente actualizan el caché de aplicación cuando el archivo de manifest cambia byte por byte. Si se cambia un recurso en caché (por ejemplo, si se actualiza la imagen header.png con nuevo contenido), se debe cambiar el contenido del archivo de manifest para que los navegadores sepan que se necesita actualizar el caché. Se puede hacer cualquier cambio al archivo de manifest, pero cambiar el número de versión es una práctica recomendada.

- -
Importante: No hay que especificar el manifest en el mismo archivo de manifest Do not specify the manifest, porque sería casi imposible informar al navegador que hay un nuevo manifest disponible.
- -

Secciones en un archivo de manifest de caché: CACHENETWORK y FALLBACK

- -

Un manifest puede tener tres secciones distintas: CACHENETWORK y FALLBACK.

- -
-
CACHE:
-
Esta es la sección predeterminada para las entradas en el archivo de manifest de caché. Los archivos listados bajo el encabezado de sección CACHE: (o inmediatamente después de la línea CACHE MANIFEST) son guardados en caché explícitamente después de ser descargados la primera vez.
-
NETWORK:
-
Los archivos listados bajo el encabezado de sección NETWORK: en el archivo de manifest de caché son recursos en lista blanca que requieren una conexión al servidor. Todos los pedidos a esos recursos evitan el caché aunque el usuario esté desconectado. Se pueden usar comodines.
-
FALLBACK:
-
La sección FALLBACK: especifica las páginas que el navegador debería usar si un recurso no es accesible. Cada entrada en esta sección lista dos URIs—lla primera es el recurso, la seguda es el fallback. Ambas URIs deben ser relativas y del mismo origen que el archivo de manifest. Se pueden usar comodines.
-
- -

Las secciones CACHENETWORK y FALLBACK pueden lsitarse en cualquier orden en el archivo de manifest y cada sección puede aparecer más de una vez en un manifest.

- -

Ejemplo 2: un archivo de manifest de caché más completo

- -

El siguiente es un archivo de manifest de caché para el sitio web imaginario en www.ejemplo.com:

- -
CACHE MANIFEST
-# v1 2011-08-14
-# Este es otro comentario
-index.html
-cache.html
-style.css
-image1.png
-
-# Usar desde la red si está disponible
-NETWORK:
-network.html
-
-# Contenido de fallback
-FALLBACK:
-/ fallback.html
-
- -

Este ejemplo usa las secciones NETWORK y FALLBACK para especificar la página network.html que deber ser recuperada desde la red y que la página fallback.html servirá como fallback (ej. en caso que una conexión al servidor no pueda establecerse).

- -

Estructura de un archivo de manifest de caché

- -

Los archivos de manifest de caché deben enviarse con el tipo MIME text/cache-manifest. Todos los recursos servidos usando este tipo MIME deben seguir la sintaxis para un manifest de caché de aplicación, como se define en esta sección.

- -

Los manifests de caché son archivos de texto en formato UTF-8 y pueden incluír opcionalmente un caracter BOM. Las nuevas líneas pueden ser representadas por salto de línea (U+000A), retorno de carro (U+000D) o ambos retorno de carro y salto de línea.

- -

La primera línea del manifest de caché debe consistir en la cadena CACHE MANIFEST (con un solo espacio U+0020 entre ambas palabras), seguido de cero o más espacios con caracteres de tabulación. Cualquier otro texto en la línea es ignorado.

- -

El resto del manifest de caché debe estar compuesto por cero o más de las siguientes líneas:

- -
-
Línea en blanco
-
Se pueden usar líneas en blanco compuestas por cero o más espacios y caracteres de tabulación.
-
Comentario
-
Los comentarios consisten en cero o más tabulaciones o espacios seguidos por un caracter # seguido de cero o más caracteres del texto del comentario. Los comentarios pueden usarse solamente en sus propias líneas y no pueden agregarse a otras líneas. Esto signifíca que no puede espcificar identificadores de fragmento.
-
Encabezado de sección
-
Los encabezados de sección especifican qué sección del manifest de caché está siendo manipulada. Hay tres encabezados de sección posibles:
-
- -
- - - - - - - - - - - - - - - - - - - -
Encabezado de secciónDescripción
CACHE:Cambia a la sección explícita del manifest de caché (esta es la sección predeterminada).
NETWORK:Cambia a la sección de lista blanca del manifest de caché.
FALLBACK:Cambia a la sección fallback del manifest de caché.
-
- -
-
La línea de encabezado de sección puede incluir espacios en blanco, pero debe incluir los dos puntos (:) en el nombre de sección.
-
Datos de sección
-
El formato de las líneas de datos varía de sección a sección. En la sección explícita (CACHE:), cada línea es una URI o referencia IRI a un recurso a guardar en caché (no se permiten caracteres comodines en esta sección). El espacio en blanco se permite antes y después de la URI o IRI en cada línea. En la sección Fallback cada línea es una URI o referencia IRI válida a un recurso, seguida por un recurso de fallback que será enviado cuando la comunicación con el servidor no pueda establecerse. En la sección Network, cada línea es una URI o referencia IRI válida a un recurso a obtener desde la red (se permite el caracter comodín * en esta sección). -
Nota: URIs relativas son relativas a la URI del manifest de caché, no a la URI del documento que hace referencia al manifest.
-
-
- -

Los archivos de manifest de caché pueden cambiar de sección a sección a voluntad (cada encabezado de sección puede usarse más de una vez) y se permite que las secciones estén vacías.

- -

Recursos en un caché de aplicación

- -

Un caché de aplicación siempre incluye al menos un recurso, identificado por URI. Todos los recursos entran en una de las siguientes categorías:

- -
-
Entradas maestras
-
Estos son recursos adicionados al caché porque un contexto de navegación visitado por el usuario incluyó un documento que indicó que estaba en caché usando el atributo manifest.
-
Entradas explícitas
-
Estos recursos están listados explícitamente en el archivo de manifest de caché de la aplicación.
-
Entradas de red
-
Estos son recursos listados en el archivo de manifest de caché de la aplicación como entradas de red.
-
Entradas de fallback
-
Estos son recursos listados en el archivo de manifest de caché de la aplicación como entradas de fallback.
-
- -
Nota: Los recursos pueden estar etiquetados en múltiples categorías y por lo tanto ser categorizados como entradas múltiples. Por ejemplo, una entrada puede ser explícita y fallback a la vez.
- -

Las categorías de recursos se describen con más detalle debajo.

- -

Entradas principales

- -

Una entrada maestra es cualquier archivo HTML que incluya un atributo {{ htmlattrxref("manifest","html") }} en su elemento {{ HTMLElement("html") }}.  Por ejemplo, digamos que tenemos el archivo http://www.ejemplo.com/entrada.html, que incluye el siguiente texto:

- -
<html manifest="ejemplo.appcache">
-  <h1>Ejemplo de cache de aplicacion</h1>
-</html>
-
- -

Si entrada.html no está listado en el archivo de manifest de caché ejemplo.appcache, visitar la pagina entrada.html causa que se agregue al caché de aplicación el archivo entrada.html como entrada maestra.

- -

Entradas explícitas

- -

Las entradas explícitas son recursos que están listados explicitamente en la seccion CACHE de un archivo de manifest de caché.

- -

Entradas de red

- -

La sección NETWORK de un archivo de manifest de caché especifíca recurso para los cuales una aplicacion web requiere acceso a internet. Las entradas de red en el caché de aplicación son escencialmente una "lista blanca online"—URIs especificadas en la sección NETWORK se cargarán desde el servidor en lugar del caché. Esto permite que el modelo de seguridad del navegador proteja al usuario de problemas de seguridad potenciales al limitar el acceso a recursos aprobados.

- -

Como ejemplo, puedes usar entradas en la seccion red para cargar y ejecutar scripts y otro código desde el servidor en lugar del caché:

- -
CACHE MANIFEST
-NETWORK:
-/api
-
- -

La sección de caché de manifest listada debajo asegura que las peticiones para cargar los recursos contenidos en  http://www.example.com/api/ siempre van a la red sin intentar acceder a la caché.

- -
Nota: Simplemente omitiendo las entradas principales (archivos que tienen el atributo manifest en el elemento html) del archivo manifest no tendrá el mismo resultado, porque las entradas principales serán agregadas—y posteriormente servida por—la aplicación de caché. 
- -

Entradas fallback

- -

Las entradas fallback son usadas cuando un intento de cargar los recursos falla. Por ejemplo, digamos que el archivo de anifest de caché http://www.example.com/example.appcache incluye el siguiente contenido:

- -
CACHE MANIFEST
-FALLBACK:
-example/bar/ example.html
-
- -

Cualquier petición a http://www.example.com/example/bar/ o cualquiera de sus directorios y su contenido hace que el explorador emita una solicitud de red al intentar cargar el recurso solicitado. Si la petición falla, debido a una falla de la red o un error de servidor de cualquier tipo, el navegador carga el archivo example.html en su lugar.

- -

Estados de caché

- -

Cada aplicación de caché tiene un estado, que indica el estado actual del caché. Cachés que comparten el mismo manifest URI comparten el mismo estado de caché, el cual puede ser uno de los siguientes:

- -
-
UNCACHED
-
Un valor especial que indica que un objeto caché de la aplicación no está inicializado en su totalidad.
-
IDLE
-
La caché de aplicación no está actualmente en el proceso de actualización.
-
CHECKING
-
El manifest se ha obtenido y revisado para actualizaciones.
-
DOWNLOADING
-
Recursos han sido descargados para ser añadidos al caché, debido a un cambio de recursos de manifest.
-
UPDATEREADY
-
Hay una nueva versión de la aplicación de caché disponible. Hay un correspondiente evento updateready, que es lanzado en lugar del evento cached cuando una nueva actualización acaba de ser descargada pero aún no ah sido activado el método swapCache().
-
OBSOLETE
-
La aplicación de caché de grupo es ahora obsoleta.
-
- -

Probando para actualizaciones para el manifest de caché

- -

Puedes programar para ver si una aplicación tiene un archivo de actualización del manifest de caché, usando JavaScript. Desde que un archio de manifest de caché tiene que ser actualizado antes de que un script adjunte eventos escuchas para probar para actualizaciones, los scripts siempre deben probar window.applicationCache.status.

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

 Para comenzar a probar manualmente para un nuevo archivo manifest, puedes usar window.applicationCache.update().

- -

Contra indicaciones

- - - -

Compatibilidad del navegador

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico4.03.510.010.64.0
-
- -
- - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico2.1{{ CompatVersionUnknown() }}{{ CompatNo() }}11.03.2
-
- -

Nota: Versiones de Firefox anteriores a la 3.5 ignoran las secciones NETWORK y FALLBACK del archivo manifest de caché.

- -

Ver también

- - - -

{{ HTML5ArticleTOC() }}

-
diff --git a/files/fr/web/html/using_the_application_cache/index.html b/files/fr/web/html/using_the_application_cache/index.html deleted file mode 100644 index bf10c6b6bd..0000000000 --- a/files/fr/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,339 +0,0 @@ ---- -title: Utiliser Application Cache -slug: Web/HTML/Using_the_application_cache -tags: - - Avancé - - Cache - - Déprécié - - Guide - - HTML - - appcache -translation_of: Web/HTML/Using_the_application_cache -original_slug: Web/HTML/Utiliser_Application_Cache ---- -
{{DefaultAPISidebar("App Cache")}}{{securecontext_header}}{{deprecated_header}}
- -
-

Attention ! L'utilisation de la fonction de mise en cache d'application décrite ici est actuellement fortement déconseillée; cette fonctionnalité est en train d' être retiré de la plate-forme Web. Utiliser Service Workers à la place. En fait, à partir de Firefox 44, quand l'application cache est utilisé pour fournir une aide hors ligne pour une page, un message d'avertissement est maintenant affiché dans la console conseillant aux développeurs d'utiliser Service workers à la place ({{bug("1204581")}}).

-
- -

Introduction

- -

HTML5 supporte la mise en cache hors-ligne de ressources d'applications web; les fichiers sont stockés dans l'Application Cache (AppCache) - une collection de ressources obtenues depuis un fichier manifest (*.appcache) inclue dans une application web.

- -

L'utilisation d'une application cache permet les bénéfices suivants :

- - - -
-

Comment fonctionne AppCache

- -

Activer AppCache

- -

Vous devez, pour utiliser le cache d'application, utiliser l'attribut manifest dans l'élément <html> comme suit :

- -
<html manifest="example.appcache">
-  ...
-</html>
- -

L'attribut manifest spécifie l'URI d'un manifeste de cache, qui est un fichier texte qui répertorie les ressources (fichiers) que le navigateur doit mettre en cache pour votre application.

- -

Vous devez inclure l'attribut manifest sur chaque page de votre application que vous souhaitez mettre en cache. Le navigateur met pas en cache les pages qui ne contiennent pas l'attribut manifest, sauf si celle-ci sont explicitement mentionnées dans le manifeste même. Vous ne devez pas lister toutes les pages que vous souhaitez mettre en cache dans le fichier manifeste, le navigateur ajoute implicitement chaque page que l'utilisateur visite et qui possède l'attribut manifest réglé sur le cache de l'application.

- -

Certains navigateurs dont Firefox vont avertir l'utilisateur la première fois que celui-ci charge votre application par une notification :

- -

« Ce site internet (www.example.com) veut stocker des données sur votre ordinateur pour une utilisation hors-ligne. [Accepter] [Refuser pour ce site] [Pas maintenant] ».

- -

Le terme « d'applications (fonctionnant) hors-ligne » est parfois utilisé pour désigner les applications que l'utilisateur a autorisé à travailler hors-ligne.

- -

Chargement des documents

- -

L'utilisation d'un cache de l'application modifie le processus normal de chargement d'un document :

- - - -

Le procédé de chargement de documents et mise à jour du cache de l'application est définie de manière plus détaillée ci-dessous:

- -
    -
  1. Quand le navigateur visite un document qui contient l'attribut manifest et qu'il n'existe pas encore de cache d'application, il chargera le document puis récupérera toutes les entrées listées dans le manifeste, créant ainsi la première version du cache d'application.
  2. -
  3. Lors des visites ultérieures de ce document, le navigateur chargera le document et les autres ressources précisées dans le manifeste à partir du cache d'application — et non du serveur. De plus, le navigateur enverra aussi un évènement checking à l'objet window.applicationCache, puis récupère le manifeste en fonction de la règle de cache HTTP adéquate.
  4. -
  5. Si la version en cache du manifeste est à jour, l'évènement noupdate est envoyé a l'applicationCache, et le processus de mise à jour est terminé. C'est la raison pour laquelle vous devez changer le manifeste chaque fois que vous mettez à jour les ressources sur le serveur, afin que le navigateur sache qu'il doit de nouveau récupérer les ressources.
  6. -
  7. Si le manifeste a changé, tous les fichiers dans le manifeste (dont ceux ajoutés au cache lors de l'appel à applicationCache.add()) sont récupérés dans un cache temporaire, en fonction des règles de cache HTTP adéquates. Un évènement progress est envoyé à l'objet applicationCache chaque fois qu'un fichier est récupéré dans le cache temporaire. Un évènement error est envoyé à chaque erreur, et la mise à jour s'arrête.
  8. -
  9. Une fois tous les fichiers récupérés en bonne et due forme, ils sont transférés dans le véritable cache hors-ligne un par un, et un évènement cached est envoyé à l'objet applicationCache. Le document étant déjà chargé dans le navigateur depuis le cache, le document mis à jour ne sera pas ré-affiché tant que celui-ci n'est pas chargé à nouveau (que ce soit manuellement ou via un programme).
  10. -
- -

Emplacement du stockage et effacement du cache hors-ligne

- -

Dans Chrome, le cache hors-ligne peut être effacé grâce au bouton "Effacer les données de navigation..." dans les préférences, ou en ouvrant chrome://appcache-internals/. Safari a un paramètre "Vider le cache" dans ses préférences, mais il est possible que le redémarrage du navigateur soit nécessaire.

- -

Dans Firefox, les données de cache hors-ligne sont stockées séparément du profil Firefox—à côté du cache disque normal :

- - - -

Dans Firefox l'état actuel du cache hors-ligne est consultable sur la page about:cache (dans la section "Offline cache device"). Le cache hors-ligne peut être effacé pour chaque site individuellement à l'aide du boutton "Supprimer..." dans  Menu -> Options -> Avancé -> Réseau -> Contenu web et données utilisateur hors connexion.

- -

Avant Firefox 11, ni Tools -> Clear Recent History ni Tools -> Options -> Advanced -> Network -> Offline data -> Clear Now ne permettaient d'effacer le cache hors-ligne. Ceci a été corrigé.

- -

Voir aussi effacer les données de stockage DOM.

- -

Les caches d'application peuvent aussi devenir obsolètes. Si le manifeste d'une application est retiré du serveur, le navigateur efface toutes les données cachées utilisant ce manifeste, et déclenche un event "obsoleted" à l'objet applicationCache. Le statut du cache de l'application est alors OBSOLETE.

- -

Le manifeste du cache

- -

Référencement d'un fichier de manifeste de cache

- -

L'attribut manifest dans une application web peut spécifier le chemin relatif d'un manifeste de cache ou une URL absolue. (Les URL absolues doivent être de la même origine que l'application). Le manifeste du cache peut avoir une extension de fichier, mais il doit être servi avec le MIME type text/cache-manifest.

- -
Note: Sur les serveurs Apache, le MIME type pour les fichiers manifest (.appcache) peut être défini par l'ajout de AddType text/cache-manifest .appcache à un fichier a .htaccess soit à l'intérieur du répertoire racine, soit le même répertoire que l'application.
- -

Les entrées dans un manifeste de cache

- -

Le fichier manifest de cache est un simple fichier de texte qui liste les ressources que le navigateur doit cache pour l'accès hors ligne. Les ressources sont identifiées par URI. Les entrées listées dans le manifeste de cache doivent avoir le même plan, hôte, et port comme un manifest.

- -

Example 1: Un fichier manifeste simple

- -

Ci-dessous, un exemple simple de manifeste — example.appcache utilisé par le site imaginaire www.example.com:

- -
CACHE MANIFEST
-# v1 - 2011-08-13
-# Ceci est un commentaire.
-https://www.example.com/index.html
-https://www.example.com/header.png
-https://www.example.com/blah/blah
-
- -

Il n'y a pas, dans cet exemple, d'en-tête de section, donc toutes les lignes sont supposées être des sections (CACHE:) explicites. On peut aussi utiliser des URL relatives (index.html, …)

- -

Le commentaire « v1 » n'est pas là par hasard : le cache n'est mis à jour que quand le manifeste change, avec une correspondance d'octet à octet. Si vous utilisez d'autres ressources (par exemple en mettant à jour le contenu de l'image header.png), vous devez changer le manifeste pour signaller au navigateur qu'il doit rafraîchir le cache, et, comme header.png est déjà présent dans le cache, vous devez modifier quelquechose d'autre. Bien que vous puissiez changer n'importe quoi d'autre dans le manifest, utiliser un numéro de version est une bonne pratique conseillée.

- -
Important: N'utilisez pas le manifeste lui-même dans le fichier de manifeste : il vous serait alors quasiment impossible d'informer le navigateur lors de la mise à jour du manifeste.
- -

Des sections dans un manifeste de cache: CACHE, NETWORK, et FALLBACK

- -

Un manifeste peut avoir trois sections distinctes: CACHE, NETWORK, et FALLBACK.

- -
-
CACHE:
-
Ceci est la section par défaut pour les entrées dans un manifeste de cache. Les fichiers sont répertoriés sous le CACHE: l'en-tête de section (ou immédiatement après la ligne MANIFESTE CACHE) est explicitement mis en cache après qu'il ait été téléchargé pour la première fois.
-
NETWORK:
-
Les fichiers répertoriés dans le NETWORK: l'en-tête de section dans le fichier manifeste de cache est une ressource de la liste blanche qui nécessite une connexion au serveur. Toutes les demandes à cette ressource contournent le cache, même si l'utilisateur est déconnecté. Le caractère générique * peut être utilisé qu'une seule fois. La plupart des sites en ont besoin *.
-
FALLBACK:
-
Le FALLBACK: section qui spécifie les pages de repli que le navigateur doit utiliser si une ressource est inaccessible. Chaque entrée dans cette section répertorie deux URIs (le premier est la ressource, le second est le repli). Les deux URIs doivent être relatif et de la même origine que le fichier manifeste. Les Wildcards peuvent être utilisés.
-
- -

Les sections CACHE, NETWORK, et FALLBACK peuvent être listés dans n'importe  quel ordre dans un manifeste de cache, et chaque section peut apparaître plus qu'une fois dans un simple manifeste.

- -

Example 2 : Un manifeste de cache plus complet

- -

Voici un exemple plus complet de manifeste pour notre site imaginaire www.example.com.

- -
CACHE MANIFEST
-# v1 2011-08-14
-# Ceci est un autre commentaire
-index.html
-cache.html
-style.css
-image1.png
-
-# Contenu Fallback
-FALLBACK:
-. fallback.html
-
-# L'utilise depuis le network (réseau) si il est disponible
-NETWORK:
-network.html
- -

Nous utilisons dans cet exemple les sections FALLBACK et NETWORK pour préciser que la page network.html doit toujours être récupérée depuis le réseau et que la page fallback.html doit être utilisée comme ressource de secours, par exemple si la connexion au serveur ne peut être établie.

- -

Structure d'un manifeste

- -

Les manifestes doivent être servis avec le type MIME text/cache-manifest, et toutes les ressources servies en utilisant ce type MIME doivent respecter la syntaxe d'un manifeste, comme défini ici.

- -

Les manifestes sont des fichiers textes au format UTF-8 et peuvent, éventuellement, inclure un caractère BOM. Les nouvelles lignes peuvent être représentés par saut de ligne (U+000A), retour chariot (U+000D), ou les deux.

- -

La première ligne du manifeste doit être la chaine CACHE MANIFEST (séparé par un simple espace U+0020), suivi par aucun ou plusieurs espaces ou tabulations. Tout autre texte sur la ligne sera ignoré.

- -

Le reste du manifeste peut contenir 0 ou plusieurs lignes :

- -
-
Lines vides
-
Vous pouvez utiliser les lignes vides comprenant 0 ou plusieurs espaces ou tabulations.
-
Commentaire
-
Les commentaires consistent en 0 ou plusieurs espaces ou tabulations suivis du caractère #, suivi de 0 ou plusieurs caractères de texte. Les commentaires devraient être utilisés seulement sur leur propre ligne, et ne devrait pas être ajoutés à d'autres lignes. Cela signifie également que vous ne pouvez pas spécifier les identifiants de fragments.
-
Section de tête
-
La section header précise la section du cache qui est manipulée. Il en existe trois types:
-
- -
- - - - - - - - - - - - - - - - - - - -
Section headerDescription
CACHE:Passe à la section explicite. C'est la section par défaut.
NETWORK:Passe à la section des sections en ligne sur la liste blanche.
FALLBACK:Passe à la section de secours.
-
- -
-
La ligne d'en-tête de section peut contenir des espaces, mais doit inclure un « : » dans le nom de la section.
-
Section data
-
Le format des lignes de données varie selon les sections. Dans la section explicite (CACHE:) chaque ligne contient une référence URI ou IRI à une ressource en cache (aucun caractère joker n'est admis dans cette section). Des espaces sont accepté avant et après l'URI on l'IRI sur chaque ligne. Dans la section de secours, chaque ligne est une référence URI ou IRI vers une ressource, suivie d'une ressource de secours qui sera utilisée lorsque la connexion au serveur ne peut être établie. Dans la section en ligne, chaque ligne est une référence valide URI ou IRI à une ressource qui sera récupérée sur le réseau (le caractère joker « * » est autorisé dans cette section). -
Note: Les URI relatives pointent vers les URI du manifeste, et non vers les URI du document qui référence le manifeste.
-
-
- -

Le manifeste peut passer à l'envie d'une section à l'autre (chaque en-tête de section peut être utilisée plusieurs fois), et les sections vides sont tolérées.

- -

Les ressources dans AppCache

- -

Le cache inclue toujours au moins une ressource, identifiée par URI. Toutes les ressources répondent à une des catégories suivantes :

- -
-
Entrées Maitres
-
Il s'agit de ressources ajoutées au cache parce qu'un contexte de navigation visité par l'utilisateur incluait un document qui indiquait que ces ressources étaient dans le cache en utilisant son attribut manifest.
-
Entrées Explicites
-
Il s'agit de ressources listées dans le manifeste du cache.
-
Entrées Network
-
Il s'agit de ressources listées dans le manifeste du cache comme entrées de network.
-
Entrées Fallback
-
Il s'agit de ressources listées dans le manifeste du cache comme entrées de fallback.
-
- -
Note : Les ressources peuvent être marquées dans plusieurs catégories, et peuvent donc être catégorisées comme des entrées multiples. Par exemple, une entrée peut être à la fois une entrée explicite et une entrée de fallback.
- -

Les catégories ressources sont décrites en détail ci-dessous.

- -

Entrées Maitres

- -

Tous les fichiers HTML peuvent inclure un attribut {{htmlattrxref("manifest","html")}} dans leur élément {{HTMLElement("html")}}. Par exemple, disons que nous avons le fichier https://www.example.com/entry.html, qui ressemble à ça :

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

Si entry.html n'est pas inclue dans le manifeste, visiter la page entry.html provoquera l'ajout de la page entry.html dans le cache de l'application comme une master entry.

- -

Entrées Explicites

- -

Les entrées explicites sont des ressources explicitement listées dans la section CACHE d'un manifeste de cache.

- -

Entrées Network

- -

Les entrées listées dans NETWORK : peuvent contenir plusieurs ou aucune ressource que l'application requiert lors d'un accès en ligne. C'est principalement une liste blanche en ligne. Les URIS spécifiées dans la section NETWORK sont chargées depuis le serveur plutôt que depuis le cache. Cela permet au modèle de sécurité du navigateur de protéger l'utilisateur de possibles brèches de sécurité en limitant l'accès aux seules ressources approuvées.

- -
Note : La liste blanche en ligne est ignorée pour les versions de Firefox antérieures à 3.5.
- -

Vous pouvez l'utiliser pour, par exemple, charger et exécuter des scripts et d'autres codes depuis le serveur au lieu du cache. :

- -
CACHE MANIFEST
-NETWORK:
-/api
-
- -

Ceci assure que les requêtes téléchargent les ressources contenues dans https://www.example.com/api/ viendront toujours du réseau sans essayer d'accéder au cache.

- -
Note : Juste omettre les master entries (les fichiers qui ont l'attribut manifest défini dans l'élément html) dans le manifeste n'aurait pas le même comportement parce que les master entries seront ajoutées — et donc servies depuis— le cache. 
- -

Entrées Fallback

- -

Les entrées de fallback sont utilisées quand une tentative de chargement d'une ressource échoue. Par exemple, imaginons qu'il y a un manifeste situé à https://www.example.com/example.appcache, et qui contient :

- -
CACHE MANIFEST
-FALLBACK:
-example/bar/ example.html
-
- -

Toute requête vers https://www.example.com/example/bar/ ou n'importe lequel de ses sous-répertoires et contenus provoquera une tentative de chargement de la ressource demandée. Si la tentative échoue, soit à cause d'un échec réseau ou d'une erreur serveur quelle qu'elle soit, le contenu du fichier example.html sera chargé à la place.

- -

Les états

- -

Chaque cache a un statut qui indique la condition actuelle du cache. Les caches qui partagent la même URI de manifeste partagent le même statut, qui est un des suivants :

- -
-
UNCACHED
-
Une valeur spéciale qui indique qu'un object application cache n'est pas complètement initialisée.
-
IDLE
-
Le cache n'est pas en cours de mise à jour.
-
CHECKING
-
Le manifeste est en train d'être contrôlé pour d'éventuelles mises à jour.
-
DOWNLOADING
-
Des ressources sont en train d'être téléchargées pour être ajoutées au cache, dû à un changement du manifeste.
-
UPDATEREADY
-
Il y a une nouvelle version du cache disponible. Il y a un évènement updateready correspondant, qui est lancé au lieu de l'évènement cached quand une nouvelle mise à jour a été téléchargée mais pas encore activée via la méthode swapCache().
-
OBSOLETE
-
Le groupe de caches est maintenant obsolète.
-
- -

Test pour les mises à jour des manifestes de cache

- -

Vous pouvez programmer un test pour voir si une application possède un manifeste de cache à jour en utilisant JavaScript. Depuis un manifeste de cache peut être été mis à jour avant un script qui teste si les événements sont à jour, les scripts doivent toujours tester window.applicationCache.status.

- -
function onUpdateReady() {
-  console.log('nouvelle version trouvée !');
-}
-window.applicationCache.addEventListener('updateready', onUpdateReady);
-if(window.applicationCache.status === window.applicationCache.UPDATEREADY) {
-  onUpdateReady();
-}
- -

Pour démarrer manuellement le test pour un nouveau manifeste de cache, vous pouvez utilisez window.applicationCache.update().

- -

Pièges

- - - -

Compatibilité des navigateurs

- - - -

{{Compat("html.elements.html.manifest")}}

- -

Voir aussi

- - -
diff --git a/files/it/web/html/using_the_application_cache/index.html b/files/it/web/html/using_the_application_cache/index.html deleted file mode 100644 index 2103febcb3..0000000000 --- a/files/it/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,384 +0,0 @@ ---- -title: Utilizzare l'application cache -slug: Web/HTML/Using_the_application_cache -translation_of: Web/HTML/Using_the_application_cache -original_slug: Web/HTML/utilizzare_application_cache ---- -

Introduzione

- -

HTML5 possiede un meccanismo di application caching che permette alle applicazioni web-based di funzionare anche offline. Gli sviluppatori possono utilizzare l'interfaccia Application Cache (AppCache)  per specificare le risorse che il browser deve memorizzare nella cache e rendere disponibili per gli utenti offline. Le applicazioni in cache si caricano e funzionano correttamente anche se gli utenti cliccano sul tasto refresh del browser quando sono offline.

- -

L'uso dell'application cache fornisce all'applicazione i seguenti benefici:

- - - -

Come funziona l'application cache

- -

Abilitare l'application cache

- -

Per abilitare l'application cache per un'applicazione, è necessario includere l'attributo {{htmlattrxref("manifest", "html")}} nell'elemento {{HTMLElement("html")}} delle pagine della tua applicazione, come mostrato nel seguente esempio:

- -
-
<html manifest="example.appcache">
-  ...
-</html>
-
-
- -

L'attributo manifest fa riferimento ad un cache manifest, un file di testo che elenca tutte le risorse (files) che il browser deve memorizzare per la tua applicazione.

- -

Bisogna includere l'attributo manifest in tutte le pagine dell'applicazione che vuoi memorizzare nella cache, il browser non memorizza le pagine che non contengono l'attributo manifest, a meno che tali pagine siano esplicitamente elencate nel file manifest stesso. Non c'è bisogno di elencare nel cache manifest tutte le pagine che si vogliono memorizzare nella cache, il browser implicitamente aggiunge ogni pagina che l'utente visita e che ha l'attributo manifest settato sull'application cache.

- -

Alcuni browser (es. Firefox) mostrano una barra di notifica la prima volta che un utente carica un'applicazione che usa l'application cache. La barra di notifica mostra un messaggio tipo:

- -

Questo sito web (www.example.com) richiede di salvare dati sul computer per l'utilizzo non in linea. [Permetti] [Mai per questo sito] [Non adesso]

- -

Il termine "offline(-enabled) applications" qualche volta fa riferimento alle applicazioni che l'utente ha esplicitamente abilitato ad utilizzare le capacità offline.

- -

Caricare documenti

- -

L'uso dell'application cache modifica il normale processo di caricamento del documento:

- - - -

Il processo di caricamento del documento ed aggiornamento dell'application cache è specificato in maggior dettaglio qui sotto:

- -
    -
  1. Quando il browser visita un documento che include l'attributo manifest, se non esiste un application cache, il browser carica il documento e poi va a prendere tutte le risorse elencate nel file manifest, creando la prima versione dell'application cache.
  2. -
  3. Nelle visite successive, il browser preleverà il documento e tutte le risorse specificate nel file manifest direttamente dall'applcation cache (non dal server). In più, il browser invia un evento checking all'oggetto window.applicationCache e processa il file manifest, seguendo le appropriate regole di chaching HTTP.
  4. -
  5. Se la copia attualmente memorizzata del manifest è aggiornata, il browser invia un evento noupdate all'oggetto applicationCache, ed il processo di aggiornamento è completo. Da notare che se viene modificata una qualsiasi delle risorse sul server, bisogna modificare anche il file manifest, in maniera tale che il browser sappia che ha bisogno di processare tutte le risorse nuovamente.
  6. -
  7. Se il file manifest è stato modificato, tutti i file elencati in esso - così come quelli aggiunti alla cache utilizzando applicationCache.add() - sono aggiunti ad una cache temporanea, seguendo le appropriate regole di caching HTTP. Per ogni file memorizzato in questa cache temporanea, il browser invia un evento progress all'oggetto applicationCache. In caso di errore, il browser invia un evento error e blocca l'aggiornamento dell'application cache.
  8. -
  9. Una volta che tutti i files sono stati recuperati con successo, vengono automaticamente spostati nella vera cache offline, e viene inviato un evento cached all'oggetto applicationCache. Dato che il documento è stato già caricato nel browser prelevandolo dalla cache, il documento aggiornato non sarà renderizzato finchè non viene ricaricato (manualmente o attraverso la programmazione).
  10. -
- -

Percorso di memorizzazione e cancellazione della cache offline

- -

Su Chrome è possibile cancellare la cache offline sia selezionando  "Clear browsing data..." dalle preferenze, oppure visitando  chrome://appcache-internals/. Safari ha una voce "Svuota cache" simile nelle sue preferenze, ma potrebbe essere necessario riavviare il browser.

- -

Su Firefox, i dati della cache offline vengono memorizzati separatamente dal profilo Firefox — insieme ai dati degli altri programmi installati:

- - - -

Su Firefox è possibile ispezionare lo stato della cache offline sulla pagina about:cache (box "Offline cache device"). La cache offline può essere cancellata separatamente per ogni sito utilizzando il tasto "Rimuovi..." presente in:
- Firefox -> Opzioni -> Avanzate -> Rete -> Dati non in linea e informazioni utente.

- -

Nelle versioni precedenti a Firefox 11, l'application cache non poteva essere cancellata utilizzando
- Tools -> Clear Recent History
- oppure
- Tools -> Options -> Advanced -> Network -> Offline data -> Clear Now Questo bug è stato fixato nelle versioni successive.

- -

Vedi anche clearing the DOM Storage data.

- -

Le application cache possono anche diventare obsolete. Se il un file manifest dell'applicazione viene rimosso dal server, il browser rimuove tutte le application cache che utilizzano quel manifest ed invia un evento "obsoleted" all'oggetto applicationCache. Questo imposta lo stato dell'application cache su OBSOLETE.

- -

Il file cache manifest

- -

Includere un file cache manifest

- -

L'attributo manifest in un'applicazione web può specificare sia il percorso relativo di un file cache manifest che un URL assoluto (gli URL assoluti devono provenire dalla stessa origine dell'applicazione). Un file cache manifest può avere diverse estensioni, ma come MIME type deve avere text/cache-manifest.

- -
Nota: Sui server Apache, il MIME type per i file manifest (.appcache) può essere impostato aggiungendo AddType text/cache-manifest .appcache ad un file .htaccess posizionato nella cartella root, oppure nella stessa cartella dell'applicazione.
- -

Le voci in un file cache manifest

- -

Il cache manifest è un semplice file di testo che elenca le risorse che il browser deve memorizzare per l'accesso offline. Le risorse sono identificate da un URI. Le voci elencate nel cache manifest devono avere lo stesso schema, host e porta come nel manifest.

- -

Esempio 1: un semplice cache manifest

- -

Il seguente è un semplice file di cache manifest, example.appcache, per un ipotetico sito web all'indirizzo 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
-
- -

Un file cache manifest può includere 3 sezioni (CACHE, NETWORK, e FALLBACK, verranno discusse in seguito). Nell'esempio qui sopra, non c'è una sezione header, quindi si assume che tutte le risorse siano elencate nell'esplicita sezione (CACHE), intendendo che il browser deve memorizzare nell'application cache tutte le risorse elencate. Le risorse possono essere specificate utilizzando sia URL assoluti che relativi (es. index.html).

- -

Il commento "v1" si trova lì per una buona ragione. I browser aggiornano  l'application cache solo se il file manifest viene modificato. Se una risorsa presente nella cache viene modificata (per esempio, viene aggiornata l'immagine header.png con un nuovo contenuto), bisogna anche cambiare il contenuto del file manifest per permettere ai browser di sapere che c'è bisogno di refreshare la cache. Si può effettuare qualsiasi modifica al file manifest, ma la best practice è modificare il numero di versione.

- -
Importante: Non includere mai il cache manifest tra le voci del file stesso, altrimenti verrà sempre prelevato dalla cache locale e sarà quasi impossibile informare il browser che un nuovo manifest è disponibile sul server.
- -

Le sezioni di un file cache manifest: CACHE, NETWORK, e FALLBACK

- -

Un manifest può avere 3 sezioni distine: CACHE, NETWORK, e FALLBACK.

- -
-
CACHE:
-
Questa è la sezione di default per le voci in un cache manifest. I files elencati sotto l'header della sezione CACHE: (oppure subito dopo la riga CACHE MANIFEST) sono esplicitamente memorizzati nella cache dopo che vengono scaricati per la prima volta.
-
NETWORK:
-
I files elencati sotto l'header della sezione NETWORK: sono risorse inserite in una white-list che richiedono una connessione al server. Tutte le richieste a queste risorse bypassano la cache, anche se l'utente è offline. È possibile utilizzare wildcards.
-
FALLBACK:
-
Nella sezione FALLBACK: vengono specificate le pagine alternative che il browser deve utilizzare nel caso una risorsa non sia accessibile. Ogni voce in questa sezione è composta da 2 URI - il primo è la risorsa, il secondo il fallback. Entrambi gli URI devono essere relativi e provenienti dalla stessa origine del file manifest. È possibile utilizzare wildcards.
-
- -

Le sezioni CACHE, NETWORK, e FALLBACK possono essere elencate in qualsiasi ordine, ogni sezione può apparire più volte nello stesso cache manifest.

- -

Example 2: un cache manifest più completo

- -

Il seguente è un esempio più completo di un cache manifest per un ipotetico sito web all'indirizzo 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
-
- -

Questo esempio utilizza le sezioni  NETWORK e FALLBACK per specificare che la pagina network.html deve essere sempre prelevata dalla rete e che la pagina fallback.html deve essere servita nel caso una risorsa non sia disponibile (es. nel caso sia impossibile stabilire una connessione col server).

- -

Struttura di un file cache manifest

- -

Un cache manifest deve essere servito con il MIME type text/cache-manifest. Tutte le risorse servite utilizzando questo MIME type devono seguire la sintassi per l'application cache manifest, come definito in questa sezione.

- -

I cache manifest sono file di testo in formato UTF-8 e possono opzionalmente contenere un carattere BOM. Gli a capo possono essere rappresentati dal line feed (U+000A), dal carriage return (U+000D), o da entrambi i caratteri.

- -

La prima riga del cache manifest deve obbligatoriamente essere la stringa CACHE MANIFEST (con un singolo spazio U+0020 tra le due parole), seguita da zero o pià caratteri di tabulazione. Qualsiasi altro testo su questa riga verrà ignorato.

- -

Il resto del manifesto cache deve essere composto da zero o più delle seguenti righe:

- -
-
Righe vuote
-
È possibile utilizzare righe vuote composte da zero o più spazi e/o caratteri di tabulazione (tab).
-
Commenti
-
I commenti consistono in zero o più tab e/o spazi seguiti da un singolo carattere #, seguito da zero o più caratteri che compongono il testo del commento. Ogni riga di commento deve essere composta in questa maniera, non esiste una coppia di delimitatori inizio/fine per wrappare intere porzioni di codice.
-
Header della sezione
-
Gli header di sezione specificano quale sezione del cache manifest stiamo per manipolare. Ci sono 3 possibili tipi di header:
-
- -
- - - - - - - - - - - - - - - - - - - -
Header di sezioneDescrizione
CACHE:Sezione che definisce quali risorse memorizzare nella cache (questa è la sezione di default, se l'header non è specificato).
NETWORK:Sezione che definisce quali risorse devono essere sempre scaricate dalla rete.
FALLBACK:Sezione che definisce dei fallback nel caso una risorsa risulti non disponibile.
-
- -
-
L'header di sezione può includere spazi, ma deve includere i due punti (:) nel nome della sezione.
-
dati della sezione
-
Il formato per le righe di dati varia da sezione a sezione. In quella esplicita (CACHE:), ogni riga è un riferimento URI o IRI valido ad una risorsa da memorizzare nella cache (non è possibile utilizzare caretteri jolly in queste sezioni). Si possono inserire spazi vuoti prima o dopo l'URI o l'IRI. Nella sezione di fallback ogni riga è un riferimento URI o IRI valido ad una risorsa, seguito dalla risorsa di fallback che deve essere servita qualndo non si può stabilire una connessione col server. nella sezione network, ogni riga è un riferimento URI o IRI valido ad una risorsa da prelevare dalla rete. (In questa sezione è consentito utilizzare il carattere jolly *). -
Note: Gli URI relativi sono relativi all'URI del cache manifest, non all'URI del documento che fa riferimento al cache manifest.
-
-
- -

I file cache manifest possono passare da una sezione all'altra a piacimento (ogni header di sezione può essere utilizzato più di una volta), le sezioni possono anche essere vuote.

- -

Risorse nell'application cache

- -

Un application cache include sempre almeno una risorsa, identificata da un URI. Tutte le risorse rientrano in una delle seguenti categorie:

- -
-
Master entries
-
Queste risorse sono aggiunte alla cache perchè sono legate ad una pagina che includeva l'attributo  manifest.
-
Explicit entries
-
Le risorse esplicitamente indicate nel cache manifest.
-
Network entries
-
Le risorse elencate nel file manifest dell'application cache che devono essere sempre recuperate dalla rete.
-
Fallback entries
-
Le risorse elencate nel file manifest che devono essere utilizzate come alternativa ad una risorsa non raggiungibile.
-
- -
Note: Una risorsa può rientrare in più categorie, per esempio può apparire sia nella sezione esplicita che in quella di fallback.
- -

Le categorie di risorse sono descritte in dettaglio qui di seguito.

- -

Master entries

- -

Le master entries sono un qualsiasi file HTML che include l'attributo {{htmlattrxref("manifest","html")}} nell'elemento {{HTMLElement("html")}}. Per esempio, diciamo che abbiamo il file HTML http://www.example.com/entry.html, composto in questa maniera:

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

se entry.html non è elencato nel file cache manifest example.appcache, basta visitare la pagina per farla aggiungere all'application cache in qualità di master entry.

- -

Explicit entries

- -

Le Explicit entries sono le risorse esplicitamente elencate in una sezione CACHE del file cache manifest.

- -

Network entries

- -

La sezione NETWORK di un cache manifest, specifica le risorse dell'applicazione web che richiedono l'accesso online. Queste voci sono essenzialmente una "online whitelist" — le URI specificate nella sezione NETWORK sono sempre caricate dal server invece che dalla cache. In questo modo il modello di sicurezza del browser protegge l'utente da potenziali falle di sicurezza limitando l'accesso alle risorse approvate.

- -

Per esempio, si può utilizzare la lista delle risorse network per caricare ed eseguire script ed altro codice dal server invece che dalla cache:

- -
CACHE MANIFEST
-NETWORK:
-/api
-
- -

La sezione del cache manifest mostrata qui sopra assicura che tutte le richieste di files contenuti nella sottocartella http://www.example.com/api/ vengano sempre caricate dalla rete senza accedere alla cache.

- -
Note: Omettere semplicemente le master entries (i files che contengono l'attributo manifest nell'elemento html) dal file manifest potrebbe non avere lo stesso risultato, perchè le master entries sarebbero scaricate solo la prima volta dalla rete, per poi essere aggiunte e prelevate dalla cache ai successivi accessi.
- -

Fallback entries

- -

Fallback entries sono utilizzate quando fallisce il tentativo di caricare una risorsa. Per esempio, diciamo che il cache manifest http://www.example.com/example.appcache includa il seguente contenuto:

- -
CACHE MANIFEST
-FALLBACK:
-example/bar/ example.html
-
- -

Qualsiasi richiesta a http://www.example.com/example/bar/ o a una qualsiasi delle sue sottocartelle ed il loro contenuto fa partire una richiesta newtwork per caricare la risorsa richiesta. Se il tentativo fallisce, a causa della connessione o di un qualsiasi errore del server, il browser carica il file example.html al suo posto.

- -

Stati della cache

- -

Ogni application cache possiede uno stato, che indica la condizione corrente della cache. Le cache che condividono la stessa URI per il manifest, condividono anche lo stesso stato della cache, che può essere uno dei seguenti:

- -
-
UNCACHED
-
Un valore speciale che indica che l'oggetto application cache non è inizializzato completamente.
-
IDLE
-
L'application cache non è attualmente in fase di aggiornamento.
-
CHECKING
-
Il manifest è in fase di prelievo e controllo aggiornamenti.
-
DOWNLOADING
-
Le risorse sono in fase di scaricamento per essere aggiunte alla cache, a causa di una risorsa modificata nel manifest.
-
UPDATEREADY
-
C'è una nuova versione dell'application cache disponibile. C'è un evento corrispondente updateready, che è lanciato al posto dell'evento cached quando un nuovo aggiornamento è stato scaricato ma non ancora attivato tramite il metodo swapCache().
-
OBSOLETE
-
Il gruppo application cache è obsoleto.
-
- -

Controllare gli aggiornamenti per il cache manifest

- -

Si può effettuare, attraverso JavaScript, un test per vedere se un'applicazione ha il cache manifest aggiornato. Dato che un cache manifest può essere stato aggiornato prima che uno script venga caricato ed attacchi un event listener per controllare gli aggiornamenti, gli script devono sempre utilizzare il test window.applicationCache.status.

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

Per testare manualmente un nuovo file manifest, è possibile utilizzare window.applicationCache.update().

- -

Trappole da evitare (aka Gotchas)

- - - -

Compatibilità con i browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support4.03.510.010.64.0
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatVersionUnknown}}{{CompatNo}}11.03.2
-
- -

Nota: Le versioni di Firefox precedenti alla 3.5 ignorano le sezioni NETWORK e FALLBACK del file cache manifest.

- -

Vedi anche

- - - -
{{HTML5ArticleTOC}}
diff --git a/files/ja/web/html/using_the_application_cache/index.html b/files/ja/web/html/using_the_application_cache/index.html deleted file mode 100644 index 56112819c3..0000000000 --- a/files/ja/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,350 +0,0 @@ ---- -title: アプリケーションキャッシュの使用 -slug: Web/HTML/Using_the_application_cache -tags: - - Advanced - - App - - Cache - - Guide - - HTML - - appcache - - application cache - - web cache -translation_of: Web/HTML/Using_the_application_cache ---- -
-

このアプリケーションキャッシュ機能を使用しないでください!これはウェブプラットフォームから削除する手続中のものです

- - -
- -
{{DefaultAPISidebar("App Cache")}}{{Deprecated_Header}}{{SecureContext_Header}}
- -

はじめに

- -

HTML5 は、ウェブアプリケーションをオフラインで実行できるようにするためのアプリケーションキャッシュの仕組みを提供しています。この Application Cache (AppCache) インターフェイスは、ブラウザーがオフラインで利用できるようにキャッシュするべきリソースを列挙します。キャッシュされたアプリケーションは、ユーザーが更新ボタンを押しても、オフラインで読み込まれて正常に動作します。

- -

アプリケーションキャッシュは以下のような利益をもたらします。

- -
-
オフラインブラウジング
-
オフライン状態であってもユーザーがサイトを閲覧できます。
-
速度
-
キャッシュされたリソースはローカルに置かれることになり、その結果、より速く読み込まれます。
-
サーバー不の削減
-
ブラウザーはサーバーから変更されたリソースのみをダウンロードします。
-
- -

アプリケーションキャッシュの動作

- -

アプリケーションキャッシュの有効化

- -

アプリケーションでアプリケーションキャッシュを有効にするには、 {{HTMLAttrxRef("manifest", "html")}} 属性をアプリケーションページ内の {{HTMLElement("html")}} 要素に設定してください。

- -
<html manifest="/example.appcache">
-  …
-</html>
-
- -

manifest 属性の値は キャッシュマニフェスト ファイルの URL を参照します。これはアプリケーションのためにブラウザーがキャッシュするべき URL を列挙したテキストファイルです。

- -

キャッシュしてほしいサイトのすべてのページに manifest 属性を含めてください。ブラウザーは manifest 属性のないページは、マニフェストファイルで列挙されていない限りキャッシュしません。マニフェストファイルにキャッシュしてほしいページをすべて列挙する必要はありません。なぜなら、ブラウザーは、ユーザーが訪問したページに manifest 属性があると、暗黙的にアプリケーションキャッシュに追加するからです。

- -

ブラウザーによっては (例: Firefox) は、ユーザーがアプリケーションキャッシュを利用するアプリケーションを読み込む初回時に通知バーを表示します。通知バーは以下のようなメッセージを表示します。

- -

このサイト (example.com) はオフライン作業用データの保存を求めています。 [許可] [このサイトでは保存しない] [今回は保存しない]

- -

「オフライン(利用可能) アプリケーション」という表現は、ときに、ユーザーがオフライン機能を利用することを許可したアプリケーションを具体的に指すこともあります。

- -

文書の読み込み

- -

アプリケーションキャッシュの利用は文書を読み込む通常のプロセスを変更します:

- - - -

文書を読み込み、アプリケーションキャッシュを更新するプロセスの詳細は以下のようになります。

- -
    -
  1. ブラウザーは manifest 属性を含む文書を訪れたとき、アプリケーションキャッシュが存在しなければ、文書を読み込んでから、マニフェストファイルに列挙されたすべてのエントリーを取得して、アプリケーションキャッシュの最初のバージョンを作成します。
  2. -
  3. その文書へのその後の訪問では、ブラウザーは文書とマニフェストファイルで指定されたその他のリソースを (サーバーからではなく) アプリケーションキャッシュから読み込みます。さらに、ブラウザーは window.applicationCache オブジェクトに checking イベントを送り、適切な HTTP キャッシュ規則に従い、マニフェストファイルを取得します。
  4. -
  5. マニフェストファイルの現在のキャッシュされたコピーが最新であった場合、ブラウザーは applicationCache オブジェクトに noupdate イベントを送り、更新プロセスは完了します。サーバー上のキャッシュされたリソースを変更する場合、マニフェストファイル自身も変更する必要があることに注意してください。そうすることで、ブラウザーはすべてのリソースを再び取得する必要があることを知ります。
  6. -
  7. マニフェストファイルが変更されていた場合、マニフェストに列挙されたファイルのすべて、および、 applicationCache.add() が呼ばれたことによってキャッシュに追加されたファイルが、適切な HTTP キャッシュ規則に従い、一時キャッシュに取得されます。この一時キャッシュに取得された各ファイル毎に、ブラウザーは applicationCache オブジェクトに progress イベントを送ります。エラーが起こった場合、ブラウザーは error イベントを送り、更新は中止されます。
  8. -
  9. すべてのファイルが正常に取得されれば、それらは本当のオフラインキャッシュに動的に移動され、applicationCache オブジェクトに cached イベントを送ります。文書は既にキャッシュからブラウザーに読み込まれているので、更新された文書は文書が(手動かプログラムで)再読込されるまで描画されません。
  10. -
- -

ストレージの場所とオフラインキャッシュをクリアする

- -

Chrome では、設定の "閲覧履歴データの消去..." を選択することか、chrome://appcache-internals/ を開くことで、オフラインキャッシュをクリアできます。Safari では、設定に、似たような "キャッシュを空にする" がありますが、ブラウザーの再起動も必要になるかもしれません。

- -

Firefox では、オフラインキャッシュデータは Firefox プロファイルに分割して保存されています。以下が通常のディスクキャッシュです:

- - - -

Firefox では、現在のステータスを about:cache ページ ("Offline cache device" の見出しがある箇所) で調査できます。オフラインキャッシュは ツール -> オプション -> 詳細 -> ネットワーク -> オフラインデータ の "削除..." ボタンを利用して各サイト毎に別々にクリアできます。

- -

Firefox 11 以前から Firefox 11 まで、ツール -> 最近の履歴を消去、あるいは、ツール -> オプション -> 詳細 -> ネットワーク -> オフラインデータ -> 今すぐ消去 のどちらでもオフラインキャッシュを消せませんでしたが、このバグは修正されました。

- -

Linux では、設定は Edit > Preferences > Advanced > Network > Offline Web Content and User Data にあります。

- -

DOM Storage データをクリアするも参照してください。

- -

アプリケーションキャッシュはもう利用されない状態にもなり得ます。アプリケーションマニフェストファイルがサーバーーから削除されたとき、ブラウザーはそのマニフェストを利用しているアプリケーションキャッシュをすべて削除し、applicationCache オブジェクトに "obsoleted" イベントを送信します。これはアプリケーションキャッシュの状態を OBSOLETE に設定します。

- -

キャッシュマニフェストファイル

- -

キャッシュマニフェストファイルを参照する

- -

ウェブアプリケーションでの manifest 属性は、キャッシュマニフェストファイルからの相対パスか絶対 URL のどちらかを指定できます。 (絶対 URL はアプリケーションと同一生成元経由でなければなりません)。キャッシュマニフェストファイルはどんなファイル拡張子でもかまいませんが、text/cache-manifest MIME タイプで提供されなければなりません。

- -
注: Apache サーバーでは、マニフェストファイル (.appcache) ファイルを設定するために、ルートディレクトリ又はアプリケーションと同じディレクトリの .htaccess ファイルに AddType text/cache-manifest .appcache を追加します。
- -

キャッシュマニフェストファイルのエントリー

- -

キャッシュマニフェストファイルはブラウザーがオフラインアクセスのためにキャッシュすべきリソースを列挙した単純なテキストファイルです。リソースは URI によって区別されます。キャッシュマニフェストに列挙されたエントリーはマニフェストと同じスキーマ、ホスト、およびポートでなければなりません。

- -

例 1: 単純なキャッシュマニフェストファイル

- -

以下は、www.example.com にある想像上のウェブサイトのための単純なキャッシュマニフェストファイルである example.appcache です。

- -
CACHE MANIFEST
-# v1 - 2011-08-13
-# これはコメントです。
-http://www.example.com/index.html
-http://www.example.com/header.png
-http://www.example.com/blah/blah
-
- -

キャッシュマニフェストファイルは3つのセクション (後述する CACHE, NETWORK, FALLBACK) を含んでいます。上記の例では、セクションヘッダーがありません。そのため、すべてのデータ行は明示的 (CACHE) セクションであるとみなされます。これは、ブラウザーは列挙されたリソースのすべてをアプリケーションキャッシュにキャッシュすべきということを意味します。リソースは絶対、もしくは、相対 URL (例:index.html) のどちらかを用いて指定できます。

- -

上記例での "v1" コメントがあるのには正当な理由があります。ブラウザーがアプリケーションキャッシュを更新するのは、マニフェストファイルがバイト単位で更新されたときだからです。キャッシュされたリソースを変更したとき (例えば、 header.png 画像を新しい画像に差し替えた場合)、ブラウザーにキャッシュの更新が必要であることを知らせるためにマニフェストファイルの内容も変更する必要があります。どんな変更でもマニフェストファイルに対して行うことができますが、バージョン番号を修正することが、おすすめできるベストプラクティスです。

- -
重要: マニフェストファイル自身をキャッシュマニフェストファイルに指定しないようにしてください。さもなければ、ブラウザーは新しいマニフェストが利用可能であることを知ることがほぼ不可能になるでしょう。
- -

キャッシュマニフェストファイルのセクション: CACHE, NETWORK, FALLBACK

- -

マニフェストには3つの性質が異なるセクション、 CACHENETWORKFALLBACK があります。

- -
-
CACHE:
-
これはキャッシュマニフェストファイルにおけるエントリーの既定のセクションです。CACHE: セクションヘッダー下 (もしくは CACHE MANIFEST の行の直後) に列挙されたファイルは、それらが初回時にダウンロードされた後に明示的にキャッシュされます。
-
NETWORK:
-
キャッシュマニフェストファイルにおける NETWORK セクションヘッダー下に列挙されたファイルは、サーバーーに接続する必要があるホワイトリスト化されたリソースです。ユーザーがオフライン状態であっても、これらのリソースへのリクエストはすべてキャッシュを無視します。ワイルドカードが利用できます。
-
FALLBACK:
-
FALLBACK: セクションは、リソースにアクセス不可能な場合にブラウザーが利用すべき代替ページを指定します。このセクションにおける各エントリーには 2 つの URI を列挙します。具体的には、最初はリソースであり、2 番目は代替リソースです。両方の URL は相対で、マニフェストファイルと同一生成元経由でなければなりません。ワイルドカードが利用できます。
-
- -

CACHE, NETWORK, FALLBACK の各セクションは、キャッシュマニフェストファイル内でどんな順番でも列挙でき、各セクションは単一のマニフェストにおいて、複数回定義することができます。

- -

例 2: より完全なキャッシュマニフェストファイル

- -

以下は、 www.example.com にある想像上のウェブサイト向けのより完全なキャッシュマニフェストファイルです:

- -
CACHE MANIFEST
-# v1 2011-08-14
-# これは別のコメントです
-index.html
-cache.html
-style.css
-image1.png
-
-# 利用可能ならネットワーク経由で利用する
-NETWORK:
-network.html
-
-# 代替コンテンツ
-FALLBACK:
-. fallback.html
-
- -

この例は NETWORKFALLBACK セクションを用いて、 network.html ページは常にネットワーク経由で取得し、 fallback.html ページは代替リソース (例えば、サーバーへの接続ができない場合) として提供されるべきであることを指定しています。

- -

キャッシュマニフェストファイルの構造

- -

キャッシュマニフェストファイルは text/cache-manifest という MIME タイプで提供される必要があります。この MIME タイプを使って提供されるすべてのリソースは、このセクションで定義されている、アプリケーションキャッシュマニフェストのための構文に従う必要があります。

- -

キャッシュマニフェストは UTF-8 形式のテキストファイルで、任意で BOM 文字を含むこともできます。改行文字は、ラインフィード (U+000A)、キャリッジリターン (U+000D)、あるいはその両方で表すことができます。

- -

キャッシュマニフェストの1行目は、ゼロあるいはそれ以上のスペースまたはタブ文字に続けて「CACHE MANIFEST」という文字列で構成される必要があります。2 つの単語の間にはひとつのスペース (U+0020) が含まれます。1行目に書かれたそれ以外の文字列は無視されます。

- -

キャッシュマニフェストの残りの部分は、ゼロあるいはそれ以上の、以下の行によって構成されます:

- -
-
空白行
-
ゼロあるいはそれ以上のスペースまたはタブ文字から成る空白行を用いることができます。
-
コメント
-
コメントは、ひとつの # 文字に続くゼロあるいはそれ以上のスペースまたはタブ文字と、それに続くゼロあるいはそれ以上のコメント文字列によって構成されます。コメントは (最初の CACHE MANIFEST 行の後の) 単独の行のみで用いることができ、他の行に付加することはできません。これは、フラグメント識別子を指定できないことを意味します。
-
セクションヘッダー
-
セクションヘッダーは、キャッシュマニフェストのどのセクションが操作されるかを示すものです。3種類のセクションヘッダーを用いることができます:
-
- -
- - - - - - - - - - - - - - - - - - - -
セクションヘッダー説明
CACHE:キャッシュマニフェストの明示的セクションに切り替えます。これは既定のセクションです。
NETWORK:キャッシュマニフェストのオンラインホワイトリストセクションに切り替えます。
FALLBACK:キャッシュマニフェストの代替セクションに切り替えます。
-
- -
-
セクションヘッダ行には空白を含めることも可能ですが、セクション名には必ずコロンを含める必要があります。
-
セクションデータ
-
データ行の形式はセクションとごとに異なります。明示的 (CACHE:) セクションでは、各行は、キャッシュのリソースを参照する妥当な URI または IRI です(このセクションではワイルドカード文字は一切利用できません)。各行の URI または IRI の前後には空白を含めることも可能です。 Fallback セクションでは、各行は、リソースと、それに続いて、サーバーとの接続ができないときに提供される代替リソースを参照する妥当な URI または IRI です。ネットワークセクションでは、各行は、ネットワークから取得できるリソースを参照する 妥当な URI または IRI です(このセクションではワイルドカード文字である * が利用できます)。 -
注意: 相対 URI は、マニフェストを参照する文書の URI ではなく、キャッシュマニフェストの URI からの相対となります。
-
-
- -

キャッシュマニフェストは、それぞれのセクションを任意で行き来することができます (つまり、各セクションヘッダを複数回用いることができます)。また、セクションを空白にしておくことも許容されています。

- -

アプリケーションキャッシュ内のリソース

- -

アプリケーションキャッシュには、少なくとも 1 つの URI で識別されるリソースが常に含まれています。すべてのリソースは以下のカテゴリのいずれかに当てはまります。

- -
-
マスターエントリ
-
これらは、ユーザーが訪問した閲覧コンテキストに、 manifest 属性を使用してこのキャッシュにあることを示す文書が含まれていたためにキャッシュに追加されたリソースです。
-
明示的なエントリ
-
これらはアプリケーションのキャッシュマニフェストファイルに明示的に掲載されているリソースです。
-
ネットワークエントリ
-
これらはアプリケーションのキャッシュマニフェストファイルにネットワークエントリとして掲載されているリソースです。
-
フォールバックエントリ
-
これらはアプリケーションのキャッシュマニフェストファイルにフォールバックエントリとして掲載されているリソースです。
-
- -
注: リソースは複数のカテゴリでタグ付けすることができるので、複数のエントリに分類することができます。例えば、エントリは明示的なエントリと予備のエントリの両方を持つことができます。
- -

リソースのカテゴリについては、以下で詳しく説明します。

- -

マスターエントリ

- -

マスターエントリとは、 {{HTMLAttrxRef("manifest", "html")}} 属性を {{HTMLElement("html")}} 要素に含む HTML ファイルのことです。例えば、http://www.example.com/entry.html という HTML ファイルがあるとします。

- -
<html manifest="example.appcache">
-  <h1>アプリケーションキャッシュの例</h1>
-</html>
-
- -

entry.htmlexample.appcache キャッシュマニフェストファイルに掲載されていない場合、 entry.html ページにアクセスすると、 entry.html がマスターエントリとしてアプリケーションキャッシュに追加されます。

- -

明示的なエントリ

- -

明示的なエントリは、キャッシュマニフェストファイルの CACHE セクションに明示的にリストされたリソースです。

- -

ネットワークエントリ

- -

キャッシュマニフェストファイルの NETWORK セクションは、ウェブアプリケーションがオンラインアクセスを必要とするリソースを指定します。アプリケーションキャッシュ内のネットワークエントリは本質的に「オンラインホワイトリスト」であり、 NETWORK セクションで指定された URI はキャッシュの代わりにサーバーから読み込まれます。これにより、ブラウザーのセキュリティモデルは、承認されたリソースへのアクセスを制限することで、潜在的なセキュリティ侵害からユーザーを保護することができます。

- -

例として、ネットワークエントリを使用して、キャッシュの代わりにサーバーからスクリプトなどのコードをロードして実行することができます。

- -
CACHE MANIFEST
-NETWORK:
-/api
-
- -

上記のキャッシュマニフェストセクションは、 http://www.example.com/api/ サブツリーに含まれるリソースをロードするリクエストが、キャッシュにアクセスしようとせずに常にネットワークに移動することを保証します。

- -
: マスターエントリ (html 要素に設定された manifest 属性を持つファイル) をマニフェストファイルから単に省略しても、マスターエントリはアプリケーションキャッシュに追加され、その後アプリケーションキャッシュから提供されるため、同じ結果にはなりません。
- -

フォールバックエントリ

- -

フォールバックエントリは、リソースの読み込みに失敗したときに使用されます。例えば、キャッシュマニフェストファイル http://www.example.com/example.appcache に以下の内容が含まれているとします。

- -
CACHE MANIFEST
-FALLBACK:
-example/bar/ example.html
-
- -

http://www.example.com/example/bar/ またはそのサブディレクトリとそのコンテンツへのリクエストにより、ブラウザーはリクエストされたリソースの読み込みを試みるためのネットワークリクエストを発行します。この試みがネットワーク障害や何らかのサーバーエラーのために失敗した場合、ブラウザーは代わりに example.html というファイルをロードします。

- -

キャッシュ状態

- -

各アプリケーションキャッシュは、キャッシュの現在の状態を示す状態を持っています。同じマニフェスト URI を共有するキャッシュは同じキャッシュの状態を共有します。

- -
-
UNCACHED
-
アプリケーションキャッシュオブジェクトが完全に初期化されていないことを示す特別な値です。
-
IDLE
-
アプリケーションキャッシュは現在更新中ではありません。
-
CHECKING
-
マニフェストを取得し、更新をチェックしています。
-
DOWNLOADING
-
リソースのマニフェストが変更されたため、キャッシュに追加するためにリソースをダウンロードしています。
-
UPDATEREADY
-
新しいバージョンのアプリケーションキャッシュが利用可能です。対応する updateready イベントがあり、新しい更新プログラムがダウンロードされたが swapCache() メソッドを使用してまだ有効化されていない場合に cached イベントの代わりに発生します。
-
OBSOLETE
-
アプリケーションキャッシュグループは廃止されました。
-
- -

キャッシュマニフェストの更新の確認

- -

JavaScript を使用して、アプリケーションが更新されたキャッシュマニフェストファイルを持っているかどうかをプログラムでテストすることができます。スクリプトが更新をテストするためにイベントリスナーをアタッチする前にキャッシュマニフェストファイルが更新されている可能性があるので、スクリプトは常に window.applicationCache.status をテストする必要があります。

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

新しいマニフェスト ファイルのテストを手動で開始するには、 window.applicationCache.update() を使用してください。

- -

Gotchas

- - - -

ブラウザーの互換性

- - - -

{{Compat("html.elements.html.manifest")}}

- -

関連情報

- - diff --git a/files/ko/web/html/using_the_application_cache/index.html b/files/ko/web/html/using_the_application_cache/index.html deleted file mode 100644 index e32a89c21a..0000000000 --- a/files/ko/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,338 +0,0 @@ ---- -title: 애플리케이션 캐시 사용하기 -slug: Web/HTML/Using_the_application_cache -translation_of: Web/HTML/Using_the_application_cache ---- -
{{DefaultAPISidebar("App Cache")}}{{SecureContext_Header}}{{Deprecated_Header}} -
-

Using the application caching feature described here is at this point highly discouraged; it’s in the process of being removed from the Web platform. Use Service Workers instead. In fact as of Firefox 44, when AppCache is used to provide offline support for a page a warning message is now displayed in the console advising developers to use Service workers instead ({{bug("1204581")}}).

-
-
- -

소개

- -

HTML5 는 웹기반의 애플리케이션들이 오프라인에서도 실행되도록 해주는 애플리케이션 캐시 메카니즘을 제공한다. 개발자는 브라우저에 캐시되어 오프라인 사용자가 사용할 수 있도록 자원을 지정하기 위하여 애플리케이션 캐시(앱 캐시) 인터페이스를 사용할 수 있다. 캐시된 애플리케이션은 사용자가 오프라인 상태에서 새로고침을 클릭할 때 올바르게 불러와서 작동한다.

- -

애플리케이션 캐시를 사용하는 것은 애플리케이션에 다음과 같은 이익을 줍니다:

- - - -

애플리케이션 캐시의 작동 방식

- -

애플리케이션 캐시 활성화 하기

- -

애플리케이션에서 애플리케이션 캐시를 활성화 하기 위해서, 먼저 당신의 애플리케이션의 페이지들의 {{HTMLElement("html")}} 엘리먼트에 {{htmlattrxref("manifest", "html")}} 속성을 추가할 필요가 있습니다:

- -
-
<html manifest="example.appcache">
-  ...
-</html>
-
- -

manifest 속성은 캐시 매니페스트 파일을 가르키며, 이는 브라우져가 당신의 애플리케이션을 위해 캐싱할 리소스(파일들)의 리스트인 텍스트 파일입니다.

- -

당신은 반드시 manifest 속성을 당신 애플리케이션의 캐싱하길 원하는 모든 페이지마다 포함시켜야합니다. The browser does not cache pages that do not contain the manifestattribute, unless such pages are explicitly listed in the manifest file itself. You do not need to list all the pages you want cached in the manifest file, the browser implicitly adds every page that the user visits and that has the manifest attribute set to the application cache.

- -

몇몇 브라우저들은(e.g., Firefox) 애플리케이션 캐시를 사용하는 애플리케이션을 처음 로드할 때 알림을 띄웁니다. 알림은 다음과 같은 메시지를 표시합니다:

- -

해당 사이트가 (www.example.com) 오프라인 사용을 위해 데이터를 저장을 요청합니다. [예] [이 사이트에서 사용안함] [나중에]

- -

The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities.

- -

documents 불러오기

- -

The use of an application cache modifies the normal process of loading a document:

- - - -

The process for loading documents and updating the application cache is specified in greater detail below:

- -
    -
  1. When the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and then fetches all the entries listed in the manifest file, creating the first version of the application cache.
  2. -
  3. Subsequent visits to that document cause the browser to load the document and other assets specified in the manifest file from the application cache (not from the server). In addition, the browser also sends a checking event to the window.applicationCache object, and fetches the manifest file, following the appropriate HTTP caching rules.
  4. -
  5. If the currently-cached copy of the manifest is up-to-date, the browser sends a noupdate event to the applicationCache object, and the update process is complete. Note that if you change any cached resources on the server, you must also change the manifest file itself, so that the browser knows it needs to fetch all the resources again.
  6. -
  7. If the manifest file has changed, all the files listed in the manifest—as well as those added to the cache by calling applicationCache.add()—are fetched into a temporary cache, following the appropriate HTTP caching rules. For each file fetched into this temporary cache, the browser sends a progress event to the applicationCache object. If any errors occur, the browser sends an error event, and the update halts.
  8. -
  9. Once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a cached event is sent to the applicationCache object. Since the document has already been loaded into the browser from the cache, the updated document will not be rendered until the document is reloaded (either manually or programatically).
  10. -
- -

Storage location and clearing the offline cache

- -

In Chrome you can clear the offline cache by selecting "Clear browsing data..." in the preferences or by visiting chrome://appcache-internals/. Safari has a similar "Empty cache" setting in its preferences but a browser restart may also be required.

- -

In Firefox, the offline cache data is stored separately from the Firefox profile—next to the regular disk cache:

- - - -

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.

- -

On Linux, you can find the setting at Edit > Preferences > Advanced > Network > Offline Web Content and User Data

- -

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 (CACHE, NETWORK, 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: CACHE, NETWORK, and FALLBACK

- -

A manifest can have three distinct sections: CACHE, NETWORK, 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 CACHE, NETWORK, 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 (after the initial CACHE MANIFEST line), 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 headerDescription
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

- - - -

브라우저 호환성

- - - -

{{Compat("html.elements.html.manifest")}}

- -

더 알아보기

- - diff --git a/files/pt-br/web/html/using_the_application_cache/index.html b/files/pt-br/web/html/using_the_application_cache/index.html deleted file mode 100644 index fc32fe9712..0000000000 --- a/files/pt-br/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,392 +0,0 @@ ---- -title: Usando cache de aplicação -slug: Web/HTML/Using_the_application_cache -tags: - - NeedsTranslation - - TopicStub -translation_of: Web/HTML/Using_the_application_cache ---- -

{{DefaultAPISidebar("App Cache")}}{{deprecated_header}}

- -
-

Usar o recurso de application caching descrito aqui é altamente desencorajado nesse momento; ele está sendo removido da plataforma Web. Em vez dele use Service Workers. De fato, a partir do Firefox 44, quando o AppCache é usado para prover suporte offline uma mensagem de alerta é exibida no console, recomendando aos desenvolvedores que usem Service workers ({{bug("1204581")}}).

-
- -

Introdução

- -

HTML5 fornece um mecanismo de cache de aplicativo que permite que aplicações baseadas na web sejam executadas offline. Os desenvolvedores podem usar a interface do cache do aplicativo (AppCache) para especificar os recursos que o navegador deve armazenar em cache e disponibilizar aos usuários offline. Os aplicativos que estão em cache de carga e funcionam corretamente, mesmo se os usuários clicarem no botão de atualização quando estão offline.

- -

Usando um cache de aplicativo dá uma aplicação os seguintes benefícios:

- - - -

Como funciona o cache de aplicativo

- -

Ativando o cache de aplicativo

- -

Para habilitar o cache de aplicativo para um aplicativo, você deve incluir o {{htmlattrxref("manifest", "html")}} atributo na {{HTMLElement("html")}} elemento em páginas de seu aplicativo, como mostrado no exemplo a seguir:

- -
-
<html manifest="example.appcache"> 
-  ...
-</html>
-
- -

O atributo manifest faz referência a um arquivo de manifesto cache, que é um arquivo de texto que lista os recursos (arquivos) que o navegador deve armazenar em cache para sua aplicação.

- -

Você deve incluir o manifest atributo em todas as páginas do seu aplicativo que você deseja armazenar em cache. O navegador não armazena em cache páginas que não contêm o manifest atributo, a menos que tais páginas são explicitamente listados no próprio arquivo de manifesto. Você não precisa listar todas as páginas que você deseja armazenar em cache no arquivo de manifesto, o navegador adiciona, implicitamente, todas as páginas que o usuário visita e que tem o manifest atributo definido para o cache do aplicativo.

- -

Alguns navegadores (por exemplo, Firefox) exibem uma barra de notificação a primeira vez que um usuário carrega um aplicativo que usa o cache do aplicativo. A barra de notificação exibe uma mensagem como esta:

- -

Este site (www.example.com) está pedindo para armazenar dados em seu computador para uso offline. . [Permitir] [Nunca para este Site] [Not Now]

- -

O termo "aplicações (habilitados) offline" às vezes se refere especificamente a aplicativos que o usuário tem permissão para usar recursos offline.

- -

Carregando documentos

- -

O uso de um cache de aplicação modifica o processo normal de carregamento de um documento:

- - - -

O processo para carregamento de documentos e actualizando o cache de aplicação é especificado em maior detalhe abaixo:

- -
    -
  1. Quando o navegador visita um documento que inclui o atributo manifest, se nenhum cache do aplicativo existe, o navegador carrega o documento e, em seguida, vai buscar todas as entradas listadas no arquivo de manifesto, criando a primeira versão do cache do aplicativo.
  2. -
  3. Visitas subseqüentes a esse documento com que o navegador para carregar o documento e outros bens especificados no arquivo de manifesto do cache de aplicativo (e não do servidor). Além disso, o navegador também envia uma checking de eventos para o window.applicationCache objeto, e vai buscar o arquivo de manifesto, seguindo as regras de cache HTTP apropriados.
  4. -
  5. Se a cópia atualmente em cache do manifesto é up-to-date, o navegador envia uma noupdate evento ao applicationCache objeto, e o processo de atualização for concluída. Note que se você alterar quaisquer recursos em cache no servidor, você também deve alterar o próprio arquivo de manifesto, de modo que o navegador sabe que precisa buscar todos os recursos novamente.
  6. -
  7. Se o arquivo de manifesto mudou, todos os arquivos listados no manifesto-bem como aqueles adicionados ao cache chamando applicationCache.add()— são buscados em um cache temporário, seguindo as regras de cache HTTP apropriados. Para cada arquivo obtidos para este cache temporário, o navegador envia um progress evento ao applicationCache objeto. Se ocorrer algum erro, o navegador envia um errorevento, e a atualização para no meio.
  8. -
  9. Depois que todos os arquivos foram recuperados com sucesso, eles são movidos para o cache off-line reais automaticamente, e um cached evento é enviado para o applicationCache objeto. Uma vez que o documento já tiver sido carregado no browser a partir do cache, o documento atualizado não será processado até que o documento é recarregado (manualmente ou através de programação).
  10. -
- -

Local de armazenamento e limpando o cache off-line

- -

No Chrome, você pode limpar o cache off-line selecionando "Limpar dados de navegação ..." nas preferências ou visitando chrome://appcache-internals/. Safari tem uma configuração semelhante "cache Empty" em suas preferências, mas uma reinicialização do navegador também pode ser necessária.

- -

No Firefox, os dados de cache offline é armazenado separadamente a partir do perfil de próxima ao cache de disco regular Firefox:

- - - -

No Firefox o status atual do cache off-line pode ser inspecionado no about:cache da página (no âmbito do "dispositivo de cache offline" designação). O cache off-line pode ser liberado para cada local separadamente utilizando o botão "Remover ..." em Ferramentas -> Opções -> Avançado -> Rede -> dados offline.

- -

Antes do Firefox 11, nem Ferramentas -> Limpar histórico recente nem Ferramentas -> Opções -> Avançado -> Rede -> dados off-line -> Limpar agora de limpar o cache offline. Isso foi corrigido.

- -

No Linux, você pode encontrar a definição em Editar> Preferências> Avançado> Rede> Off-line de conteúdo da Web e dados de usuário

- -

Veja também a limpeza de dados de armazenamento DOM .

- -

Caches de aplicativos também podem se tornar obsoletos. Se o arquivo de manifesto de um aplicativo é removido do servidor, o navegador remove todos os caches de aplicativos que usam esse manifesto, e envia um evento "obsoleto" para o applicationCache objeto. Isso define o estado do cache do aplicativo para OBSOLETE .

- -

O arquivo de manifesto de cache

- -

Fazendo referência a um arquivo de manifesto de cache

- -

manifest atributo em uma aplicação web pode especificar o caminho relativo de um arquivo de manifesto de cache ou um URL absoluto. (Absolute URLs devem ser da mesma origem que a aplicação). Um arquivo de manifesto de cache pode ter qualquer extensão de arquivo, mas ele deve ser servido com o tipo MIME text/cache-manifest .

- -
Nota: Em servidores Apache, o tipo MIME para manifesto (.appcache) arquivos podem ser definidos pela adição de AddType text/cache-manifest .appcache em um arquivo .htaccess, no o diretório raiz, ou o mesmo diretório do aplicativo.
- -

As entradas de um arquivo de manifesto de cache

- -

O arquivo de manifesto cache é um simples arquivo de texto que lista os recursos do navegador deve armazenar em cache para acesso offline. Os recursos são identificados pelo URI. Entradas listadas no manifesto de cache deve ter o mesmo esquema, host e porta que o manifesto.

- -

Exemplo 1: um arquivo de manifesto de cache simples

- -

O que se segue é um arquivo de manifesto de cache simples, example.appcache , para um web site imaginário em 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
-
- -

Um arquivo de manifesto de cache pode incluir três secções ( CACHE , NETWORK , e FALLBACK , discutidas abaixo). No exemplo acima, não há cabeçalho de seção, para que todos os dados linhas estão a ser assumida no explícita ( CACHE seção), o que significa que o navegador deve armazenar em cache todos os recursos listados no cache do aplicativo. Os recursos podem ser especificados usando URLs absoluto ou relativo (por exemplo, index.html ).

- -

O comentário "v1" no exemplo acima está lá por um bom motivo. Browsers apenas atualizar um cache de aplicativo quando o arquivo de manifesto muda, byte por byte. Se você alterar um recurso de cache (por exemplo, você atualizar o header.png imagem com novo conteúdo), você também deve alterar o conteúdo do arquivo de manifesto, a fim de permitir que os navegadores sabem que precisam para atualizar o cache. Você pode fazer qualquer mudança que você quer o arquivo de manifesto, mas revisando um número de versão é a melhor prática recomendada.

- -
Importante: Não especificar a manifestar-se no arquivo de manifesto cache, caso contrário, será quase impossível para informar o navegador de um novo manifesto está disponível.
- -

Seções em um arquivo de manifesto de cache: CACHE , NETWORK , e FALLBACK

- -

Um manifesto pode ter três secções distintas: CACHE , NETWORK , e FALLBACK .

- -
-
CACHE:
-
Esta é a seção padrão para entradas em um arquivo de manifesto cache. Os arquivos listados sob o CACHE: cabeçalho de seção (ou imediatamente após o CACHE MANIFEST line) são explicitamente em cache depois do download pela primeira vez.
-
NETWORK:
-
Os arquivos listados sob a NETWORK: cabeçalho de seção no arquivo de manifesto de cache são recursos enumerados na lista branca que requerem uma conexão com o servidor. Todas as solicitações para tais recursos ignorar o cache, mesmo se o usuário estiver offline. O caractere curinga * pode ser usado uma vez. A maioria dos sites precisam * .
-
FALLBACK:
-
FALLBACK: seção especifica páginas fallback o navegador deve usar se um recurso é inacessível. Cada entrada nesta secção enumera duas URIs-o primeiro é o recurso, o segundo é o fallback. Ambos os URIs deve ser relativo e da mesma origem do arquivo de manifesto. Curingas podem ser usados.
-
- -

Os CACHE , NETWORK e FALLBACK seções podem ser listados em qualquer ordem em um arquivo de manifesto cache, e cada seção pode aparecer mais de uma vez em um único manifesto.

- -

Exemplo 2: um arquivo de manifesto de cache mais completo

- -

O seguinte é um arquivo de manifesto de cache mais completo para o web site imaginário em 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
-
- -

Este exemplo usa NETWORK e FALLBACK seções para especificar que o network.html página deve sempre ser recuperada a partir da rede, e que ofallback.html página deve ser servido como um recurso fallback (por exemplo, no caso de uma conexão com o servidor não pode ser estabelecida ).

- -

Estrutura de um arquivo de manifesto de cache

- -

Cache arquivos de manifesto deve ser servido com o text/cache-manifest tipo MIME. Todos os recursos servido usando este tipo MIME deve seguir a sintaxe para um manifesto do cache do aplicativo, conforme definido nesta seção.

- -

Manifestos de cache são UTF-8 arquivos de texto formato, e pode incluir, opcionalmente, um personagem BOM. Newlines pode ser representado por avanço de linha ( U+000A ), retorno de carro ( U+000D ), ou retorno de carro e alimentação de linha ambos.

- -

A primeira linha do manifesto de cache deve consistir da seqüência de CACHE MANIFEST (com um único U+0020 o espaço entre as duas palavras), seguido de zero ou mais espaço ou tabulação caracteres. Qualquer outro texto na linha é ignorado.

- -

O restante do manifesto cache deve ser composta de zero ou mais das seguintes linhas:

- -
-
Linha em branco
-
Você pode usar linhas em branco composta de zero ou mais de espaço e caracteres de tabulação.
-
Comentário
-
Comentários consistem em zero ou mais abas ou espaços seguidos por um único # caracteres, seguido por zero ou mais caracteres de texto de comentário. Comentários só pode ser utilizado em suas próprias linhas (após a linha MANIFESTO CACHE inicial), e não pode ser adicionado a outras linhas. Isso significa que você não pode especificar identificadores de fragmentos.
-
Cabeçalho da seção
-
Cabeçalhos de seção especificar qual seção do manifesto cache está sendo manipulado. Há três cabeçalhos de seção possíveis:
-
- -
- - - - - - - - - - - - - - - - - - - -
Cabeçalho da seçãoDescrição
CACHE:Muda para a seção explícita do manifesto de cache (esta é a seção padrão).
NETWORK:Muda para a seção whitelist linha do manifesto de cache.
FALLBACK:Muda para a seção de fallback do manifesto de cache.
-
- -
-
A linha de cabeçalho da seção pode incluir espaços em branco, mas deve incluir os dois pontos ( : ) no nome da seção.
-
Seção de dados
-
O formato de linhas de dados varia de uma seção para outra. No explícita ( CACHE: ) seção, cada linha é um URI ou IRI referência válida para um recurso para cache (sem caracteres curinga são permitidos neste seções). Espaços em branco são permitidas antes e depois da URI ou IRI em cada linha. Na secção Fallback cada linha é um URI ou IRI referência válida para um recurso, seguido de um recurso de reversão que é para ser servido para cima quando uma ligação com o servidor não pode ser feito. Na seção de rede, cada linha é um URI ou IRI referência válida para um recurso para buscar a partir da rede (ou o caractere curinga * pode ser usado nesta seção).
-
-
Nota: Os URIs relativos são em relação ao URI do manifesto de cache, não para o URI do documento que faz referência ao manifesto.
-
-
- -

Cache arquivos de manifesto pode mudar de uma seção para outra à vontade (cada cabeçalho de seção pode ser usada mais de uma vez), e as seções estão autorizados a estar vazio.

- -

Recursos do cache de aplicativo

- -

Um cache de aplicativo inclui sempre pelo menos um recurso, identificado por URI. Todos os recursos se enquadrar em uma das seguintes categorias:

- -
-
Entradas Mestre
-
Trata-se de recursos adicionais para o cache porque um contexto de navegação visitado pelo usuário incluído um documento que indicava que era neste cache usando seu manifest atributo.
-
Entradas explícitas
-
Estes são os recursos expressamente enumeradas no arquivo de manifesto de cache do aplicativo.
-
Entradas de rede
-
Estes são os recursos enumerados no cache de arquivos de manifesto do aplicativo como entradas de rede.
-
Entradas de fallback
-
Estes são os recursos enumerados no cache de arquivos de manifesto do aplicativo como entradas de fallback.
-
- -
Nota: Os recursos podem ser marcados com múltiplas categorias, e pode portanto ser categorizadas como entradas múltiplas. Por exemplo, uma entrada pode ser tanto uma entrada explícita e uma entrada de fallback.
- -

As categorias de recursos são descritos em maior detalhe abaixo.

- -

Entradas Mestre

- -

Entradas Master são todos os arquivos HTML que incluem um {{htmlattrxref("manifest","html")}} em seu atributo {{HTMLElement("html")}}  elemento. Por exemplo, vamos dizer que temos o arquivo HTML http://www.example.com/entry.html, que se parece com isso:

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

Se entry.html não está listado no example.appcache arquivo de manifesto cache, visitando o entry.html página faz com que entry.html a ser adicionado ao cache de aplicativo como uma entrada de mestre.

- -

Entradas explícitas

- -

Entradas explícitas são recursos que estão listados explicitamente na CACHE seção de um arquivo de manifesto cache.

- -

Entradas de rede

- -

NETWORK seção de um arquivo de manifesto de cache especifica recursos para que uma aplicação web requer acesso online. Entradas de rede em um cache de aplicativo são essencialmente um -URIs "whitelist on-line" especificadas na NETWORK seção são carregados a partir do servidor em vez do cache.Isso permite que o modelo de segurança do navegador proteger o usuário de possíveis violações de segurança, limitando o acesso aos recursos aprovados.

- -

Como exemplo, você pode usar as entradas de rede para carregar e executar scripts e outros códigos do servidor em vez do cache:

- -
CACHE MANIFEST
-NETWORK:
-/api
-
- -

A seção manifesto de cache listados acima assegura que os pedidos para carregar recursos contidos no http://www.example.com/api/ subtree sempre ir para a rede sem tentar acessar o cache.

- -
Nota: A simples omissão entradas master (arquivos que têm o manifest atributo definido no html elemento) a partir do arquivo de manifesto não teria o mesmo resultado, pois as entradas de mestre será acrescentado e, posteriormente, servido a partir das-o cache do aplicativo.
- -

Entradas de fallback

- -

Entradas de fallback são usados ​​quando uma tentativa de carregar um recurso falhar. Por exemplo, digamos que o arquivo de manifesto de cache http://www.example.com/example.appcache  inclui o seguinte conteúdo:

- -
CACHE MANIFEST
-FALLBACK:
-example/bar/ example.html
-
- -

Qualquer pedido de http://www.example.com/example/bar/ ou qualquer de seus subdiretórios e seu conteúdo com que o navegador para emitir uma solicitação de rede para tentar carregar o recurso solicitado. Se a tentativa falhar, devido a uma falha de rede ou um erro no servidor de algum tipo, o navegador carrega o arquivo example.html.

- -

Estados do cache

- -

Cada cache de aplicativo tem um estado, o que indica a condição atual do cache. Caches que compartilham o mesmo URI manifesto compartilham o mesmo estado de cache, o que pode ser um dos seguintes procedimentos:

- -
-
UNCACHED
-
Um valor especial que indica que um objeto de cache do aplicativo não está totalmente inicializado.
-
IDLE
-
O cache de aplicativo não está neste momento em processo de ser atualizado.
-
CHECKING
-
O manifesto está sendo buscado e verificado se há atualizações.
-
DOWNLOADING
-
Os recursos estão sendo baixados para ser adicionado ao cache, devido a um manifesto de recursos alterado.
-
UPDATEREADY
-
Há uma nova versão do cache do aplicativo disponível. Há um correspondente updateready evento, que é acionado em vez do cached de eventos quando uma nova atualização já foi baixado, mas ainda não activado através do swapCache() método.
-
OBSOLETE
-
O grupo de cache do aplicativo é agora obsoleto.
-
- -

Testando se há atualizações para o manifesto de cache

- -

Você pode programaticamente testar para ver se um aplicativo tem um arquivo de manifesto cache atualizado, usando JavaScript. Uma vez que um arquivo de manifesto de cache pode ter sido atualizado antes de um script atribui ouvintes de eventos para testar atualizações, os scripts deve sempre testarwindow.applicationCache.status .

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

Para iniciar manualmente o teste para um novo arquivo de manifesto, você pode usar window.applicationCache.update() .

- -

Recomendações

- - - -

Compatibilidade do navegador

- -
{{CompatibilityTable}}
- -
-
- - - - - - - - - - - - - - - - - - - -
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico4.0{{CompatGeckoDesktop("1.9.1")}}[1]10.010.64.0
-
- -
- - - - - - - - - - - - - - - - - - - - - -
RecursoAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Suporte básico2.1{{CompatVersionUnknown}}1.0.1[2]11.0[3]11.03.2
-
-
- -
 
- -

Nota: [1] As versões do Firefox antes de 3,5 ignora as seções da rede e fallback do arquivo de manifesto cache.
-           [2] Quando usar AppCache para prover compatibilidade offline no FirefoxOS hosted App, você necessita declarar no arquivo manifest.webapp . Procure mais informações no campo appcache_path.
-           [3] Recarregar a página no Internet Explorer móvel irá limpar o cache da aplicação, então a página irá falhar. No entanto, fechar a página e abrir via favoritos, funcionará novamente.

- -

Veja também

- - - -
{{HTML5ArticleTOC}}
-
diff --git a/files/pt-pt/web/html/using_the_application_cache/index.html b/files/pt-pt/web/html/using_the_application_cache/index.html deleted file mode 100644 index d57bd276b8..0000000000 --- a/files/pt-pt/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,343 +0,0 @@ ---- -title: Utilizar a cache de aplicação -slug: Web/HTML/Using_the_application_cache -tags: - - Aplicação - - App - - Avançado - - Cache - - Guía - - HTML - - appcahe - - cache da aplicação - - cache da web - - web cache -translation_of: Web/HTML/Using_the_application_cache -original_slug: Web/HTML/Utilizar_a_cache_de_aplicacao ---- -
{{DefaultAPISidebar("App Cache")}}{{SecureContext_Header}}{{Deprecated_Header}} -
-

Using the application caching feature described here is at this point highly discouraged; it’s in the process of being removed from the Web platform. Use Service Workers instead. In fact as of Firefox 44, when AppCache is used to provide offline support for a page a warning message is now displayed in the console advising developers to use Service workers instead ({{bug("1204581")}}).

-
-
- -

Introdução

- -

HTML5 provides an application caching mechanism that lets web-based applications run offline. Developers can use the Application Cache (AppCache) interface to specify resources that the browser should cache and make available to offline users. Applications that are cached load and work correctly even if users click the refresh button when they are offline.

- -

Using an application cache gives an application the following benefits:

- - - -

Como é que funciona a cache de aplicação

- -

Ativar a cache de aplicação

- -

To enable the application cache for an application, you must include the {{HTMLAttrxRef("manifest", "html")}} attribute in the {{HTMLElement("html")}} element in your application's pages, as shown in the following example:

- -
<html manifest="example.appcache">
-  ...
-</html>
-
- -

The manifest attribute references a cache manifest file, which is a text file that lists resources (files) that the browser should cache for your application.

- -

You should include the manifest attribute on every page of your application that you want cached. The browser does not cache pages that do not contain the manifest attribute, unless such pages are explicitly listed in the manifest file itself. You do not need to list all the pages you want cached in the manifest file, the browser implicitly adds every page that the user visits and that has the manifest attribute set to the application cache.

- -

Some browsers (e.g., Firefox) display a notification bar the first time a user loads an application that uses the application cache. The notification bar displays a message such as:

- -

This website (www.example.com) is asking to store data on your computer for offline use. [Allow] [Never for This Site] [Not Now]

- -

The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities.

- -

Carregar documentos

- -

The use of an application cache modifies the normal process of loading a document:

- - - -

The process for loading documents and updating the application cache is specified in greater detail below:

- -
    -
  1. When the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and then fetches all the entries listed in the manifest file, creating the first version of the application cache.
  2. -
  3. Subsequent visits to that document cause the browser to load the document and other assets specified in the manifest file from the application cache (not from the server). In addition, the browser also sends a checking event to the window.applicationCache object, and fetches the manifest file, following the appropriate HTTP caching rules.
  4. -
  5. If the currently-cached copy of the manifest is up-to-date, the browser sends a noupdate event to the applicationCache object, and the update process is complete. Note that if you change any cached resources on the server, you must also change the manifest file itself, so that the browser knows it needs to fetch all the resources again.
  6. -
  7. If the manifest file has changed, all the files listed in the manifest—as well as those added to the cache by calling applicationCache.add()—are fetched into a temporary cache, following the appropriate HTTP caching rules. For each file fetched into this temporary cache, the browser sends a progress event to the applicationCache object. If any errors occur, the browser sends an error event, and the update halts.
  8. -
  9. Once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a cached event is sent to the applicationCache object. Since the document has already been loaded into the browser from the cache, the updated document will not be rendered until the document is reloaded (either manually or programatically).
  10. -
- -

Localização do armazenamento e limpeza off-line da cache

- -

In Chrome you can clear the offline cache by selecting "Clear browsing data..." in the preferences or by visiting chrome://appcache-internals/. Safari has a similar "Empty cache" setting in its preferences but a browser restart may also be required.

- -

In Firefox, the offline cache data is stored separately from the Firefox profile—next to the regular disk cache:

- - - -

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.

- -

On Linux, you can find the setting at Edit > Preferences > Advanced > Network > Offline Web Content and User Data

- -

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.

- -

O ficheiro manifest da cache

- -

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 (CACHE, NETWORK, 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: CACHE, NETWORK, and FALLBACK

- -

A manifest can have three distinct sections: CACHE, NETWORK, 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. The wildcard character * can be used once. Most sites need *.
-
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 CACHE, NETWORK, 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 (after the initial CACHE MANIFEST line), 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:
-
- -
- - - - - - - - - - - - - - - - - - - -
Secção cabeçalhoDescrição
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.
-
Dados da secção
-
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 (or the wildcard character * can be used in this section). -
Nota: 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.

- -

Recursos na cache de aplicação

- -

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.
-
- -
Nota: 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.

- -

Estados da cache

- -

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() {
-  console.log('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

- - - -

Compatibilidade de navegador

- - - -

{{Compat("html.elements.html.manifest")}}

- -

Consultar também

- - diff --git a/files/ru/web/html/using_the_application_cache/index.html b/files/ru/web/html/using_the_application_cache/index.html deleted file mode 100644 index ccd169e6a8..0000000000 --- a/files/ru/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,329 +0,0 @@ ---- -title: Использование кеширования приложений -slug: Web/HTML/Using_the_application_cache -translation_of: Web/HTML/Using_the_application_cache -original_slug: Web/HTML/Использование_кеширования_приложений ---- -

Введение

-

HTML5 предоставляет механизм кеширования приложения, позволяющий веб-приложениям работать в автономном режиме. Разработчики теперь могут использовать интерфейс Кеша приложения (AppCache), сообщая браузеру, какие из ресурсов браузеру следует закешировать и сделать доступными в режиме офлайн. Закодированные приложения загружаются и работают корректно, даже если пользователь обновляет страницу в тот момент, когда он отключён от сети.

-

Использование механизма кеширования даёт следующие преимущества:

- -

Как работает кеш приложения

-

Включение механизма кеширования

-

Для включения механизма кеширования приложения вам необходимо включить атрибут {{htmlattrxref("manifest", "html")}} в элемент {{HTMLElement("html")}} на странице вашего приложения, как показано примере ниже:

-
-
<html manifest="example.appcache">
-  ...
-</html>
-
-
-

Атрибут manifest ссылается на файл манифеста кеша, который является текстовым файлом и содержит список ресурсов (файлов), которые браузеру следует закешировать для вашего приложения.

-

Вам следует включить атрибут manifest в каждую страницу вашего приложения, внутри которой вы хотели бы осуществлять кеширование. Браузер не закеширует страницы, не содержащие атрибута manifest, пока такие страницы не будут явно указаны в файле манифеста. Вам не обязательно перечислять все страницы, которые вы хотите закешировать, в файле манифеста, т.к. браузер неявно добавляет в кеш приложения каждую посещаемую пользователем страницу, где есть атрибут  manifest.

-

Некоторые браузеры (например, Firefox) показывают панель уведомлений , когда пользователь загружает использующее кеш приложение в первый раз. Панель уведомлений может показывать примерно такое сообщение::

-

Этот веб-сайт (www.example.com) запрашивает у вас разрешение на хранение данных для автономной работы на вашем компьютере. [Разрешить] [Никогда для этого сайта] [Не сейчас]

-

Термин "офлайн(-доступные) приложения" иногда относится конкретно к приложениям, которым пользователь разрешил использовать возможности работы офлайн.

-

Загрузка документов

-

Использование кеша приложений изменяет обычный процесс загрузки документа:

- -

Ниже приведено более подробное описание процесса загрузки документов и обновления кеша приложения:

-
    -
  1. Когда браузер посещает страницу со включённым атрибутом manifest и кеша приложения не существует, браузер загружает документ, а затем получает все пункты файла манифеста, создавая тем самым первую версию кеша приложения.
  2. -
  3. Последующие посещения данной страницы приводят к загрузке документа и других ресурсов, указанных в файле манифеста, уже из кеша приложения (не с сервера). К тому же браузер также посылает событие checking объекту window.applicationCache и получает файл манифеста в соответствии с правилами кеширования HTTP.
  4. -
  5. Если текущая закешированная копия манифеста совпадает со скачанной, браузер посылает событие noupdate объекту applicationCache, завершая процесс обновления. Обратите внимание, если вы изменили закешированные ресурсы на стороне сервера, вам также необходимо изменить и файл манифеста, тем самым давая браузеру знать, какие из ресурсов нужно получить повторно.
  6. -
  7. Если файл манифеста изменился, то все перечисленные в нём файлы, так же, как и добавленные в кеш с помощью вызова applicationCache.add(), попадают во временный кеш с учётом правил кеширования HTTP. Во время обновления каждого файла в этом временном кеше браузер посылает событие progress объекту applicationCache. Если происходит ошибка, браузер посылает событие error, а обновление прекращается.
  8. -
  9. Как только успешно получены все файлы, они автоматически отправляются в настоящий офлайн-кеш, а объекту applicationCache посылается событие cached. Поскольку документ уже был загружен в браузер из кеша, обновлённый документ не перерисуется, пока страница не будет перезагружена (неважно как, вручную или программно).
  10. -
-

Место хранения и очистка офлайн-кеша

-

В Chrome офлайн-кеш можно очистить, выбрав «Очистить историю...» в настройках или перейдя на адрес chrome://appcache-internals/. У Safari также есть похожий пункт «Очистить кеш» в настройках, но для этого также может  понадобиться перезапуск браузера.

-

Firefox хранит данные офлайн-кеша отдельно от профиля — по соседству с обычным дисковым кешем:

- -

Текущее состояние офлайн-кеша в Firefox можно посмотреть на странице about:cache (в разделе «Offline cache device»). Офлайн-кеш можно очистить по отдельности для каждого сайта, используя кнопку «Удалить...» в разделе Инструменты -> Настройки -> Дополнительные -> Сеть -> Автономное содержимое.

-

До Firefox 11 кеш нельзя было очистить ни кнопкой Инструменты -> Удалить недавнюю историю, ни Инструменты -> Настройки -> Дополнительные -> Сеть -> Автономное содержимое -> Очистить сейчас. Сейчас эта проблема устранена.

-

В Linux настройки офлайн-кеша можно найти в разделе Инструменты -> Настройки -> Дополнительные -> Сеть -> Автономное содержимое и данные пользователя

-

Смотрите также очистка данных хранилища DOM.

-

Также кеши приложения могут устареть. Если с сервера удалить файл манифеста, браузер удалит все кеши, которые были в нём указаны, и пошлёт событие obsoleted объекту applicationCache, что установит состояние кеша в OBSOLETE.

-

Файл манифеста кеша

-

Ссылки на файл манифеста кеша

-

Атрибут manifest может содержать как относительный путь, так и абсолютный URL (который должен соответствовать принципу единого источника) к файлу манифеста. Файл манифеста кеша может иметь любое расширение, но его MIME- тип должен быть text/cache-manifest.

-
- Примечание: На серверах Apache MIME-тип файлов манифеста (.appcache) можно настроить, добавив строчку AddType text/cache-manifest .appcache в файл .htaccess в корневой директории или же директории приложения.
-

Пункты манифеста кеша

-

Манифест кеша представляет собой обычный текстовый файл, содержащий список ресурсов, которые браузеру следует закешировать для обеспечения автономного доступа. Ресурсы идентифицируются по URI. Объекты, перечисленные в манифесте кеша должны иметь те же протокол, хост и порт, что и сам манифест.

-

Пример 1: простой файл манифеста кеша

-

Ниже приведено содержимое простого файла манифеста кеша для воображаемого веб-сайта www.example.com.

-
CACHE MANIFEST
-# v1 - 2011-08-13
-# Это комментарий.
-http://www.example.com/index.html
-http://www.example.com/header.png
-http://www.example.com/blah/blah
-
-

Манифест кеша может включать три секции (CACHE, NETWORK и FALLBACK, которые будут рассмотрены далее). В приведённом примере нет заголовков секций, поэтому предполагается, что все строчки находятся в явной секции CACHE,  подразумевая, что все указанные в них ресурсы браузеру следует сохранить в кеше приложения. Ресурсы могут быть указаны с использованием как абсолютных, так и относительных URL (например, index.html).

-

Для наличия в кеше комментария «v1» есть веские основания. Браузер обновляет кеш приложения, только если изменён файл манифеста, хотя бы один байт в нём. Если вы изменяете закешированный ресурс на стороне сервера, (например, при обновлении содержимого картинки  header.png), вы также должны изменить содержимое файла манифеста, тем самым сообщая браузеру, что нужно обновить кеш. Вы можете изменять файл манифеста так, как вам угодно, но лучшие практики рекомендуют использовать изменение номера пересмотра.

-
- - Важное замечание: Не указывайте в манифесте ссылку на него самого, в противном случае будет невозможно сообщить браузеру о том, что кеш обновился.
-

Sections in a cache manifest file: CACHE, NETWORK, and FALLBACK

-

A manifest can have three distinct sections: CACHE, NETWORK, 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 CACHE, NETWORK, 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 (after the initial CACHE MANIFEST line), 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 headerDescription
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

- -

Browser compatibility

-

{{CompatibilityTable}}

-
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support4.03.510.010.64.0
-
-
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatVersionUnknown}}{{CompatNo}}11.03.2
-
-

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

-

See also

- diff --git a/files/zh-cn/web/html/using_the_application_cache/index.html b/files/zh-cn/web/html/using_the_application_cache/index.html deleted file mode 100644 index 5a4f2c132b..0000000000 --- a/files/zh-cn/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,401 +0,0 @@ ---- -title: 使用应用缓存 -slug: Web/HTML/Using_the_application_cache -tags: - - App 缓存 - - HTML - - HTML5 - - Service Workers - - Web 缓存 - - application cache - - 已弃用 - - 应用缓存 - - 指南 -translation_of: Web/HTML/Using_the_application_cache ---- -

{{DefaultAPISidebar("App Cache")}}{{deprecated_header}}

- -
-

在此刻使用这里描述的应用程序缓存功能高度不鼓励; 它正在处于从Web平台中被删除的过程。请改用Service Workers 代替。事实上,在Firefox 44中,当AppCache用于为页面提供离线支持时,控制台中现在显示一条警告消息,建议开发人员改用 Service workers 代替 ({{bug(1204581)}})。

-
- -

简介

- -
HTML5 提供一种 应用程序缓存 机制,使得基于web的应用程序可以离线运行。开发者可以使用 Application Cache (AppCache接口设定浏览器应该缓存的资源并使得离线用户可用。 在处于离线状态时,即使用户点击刷新按钮,应用也能正常加载与工作。
- -
-

使用应用缓存可以得到以下益处:

- - - -

应用缓存如何工作

- -

启用应用缓存

-若想为应用启用应用缓存,你需要在应用页面中的 {{HTMLElement("html")}} 元素上增加 {{htmlattrxref("manifest", "html")}} 特性,请看下面的例子:
- -
-
-
<html manifest="example.appcache"> 
-  ...
-</html>
-
-
- -

manifest 特性与 缓存清单(cache manifest) 文件关联,这个文件包含了浏览器需要为你的应用程序缓存的资源(文件)列表。

- -

你应当在每一个意图缓存的页面上添加 manifest 特性。浏览器不会缓存不带有manifest 特性的页面,除非这个页面已经被写在清单文件内的列表里了。你没有必要添加所有你意图缓存的页面的清单文件,浏览器会暗中将用户访问过的并带有 manifest 特性的所有页面添加进应用缓存中。

- -

有些浏览器,比如说firefox,当用户首次加载一个需要使用应用缓存的应用时,会显示一个提示栏。提示信息如下:

- -

该站点 (www.example.com) 请求在你的电脑上存储数据以供离线使用。[允许] [对此站点永不允许] [暂时不允许]

- -

术语 「offline(-enabled) applications」 很多情况下指用户已经允许使用离线存储的程序。

- -

加载文档

- -
-

application cache的使用会修改文档的加载过程:

- -
    -
  • 如果应用缓存存在,浏览器直接从缓存中加载文档与相关资源,不会访问网络。这会提升文档加载速度。
  • -
  • 浏览器检查清单文件列出的资源是否在服务器上被修改。
  • -
  • 如果清单文件被更新了, 浏览器会下载新的清单文件和相关的资源。 这都是在后台执行的,基本不会影响到webapp的性能。
  • -
- -

下面详细描述了加载文档与更新应用缓存的流程:

-
- -
    -
  1. 当浏览器访问一个包含 manifest 特性的文档时,如果应用缓存不存在,浏览器会加载文档,然后获取所有在清单文件中列出的文件,生成应用缓存的第一个版本。
  2. -
  3. 对该文档的后续访问会使浏览器直接从应用缓存(而不是服务器)中加载文档与其他在清单文件中列出的资源。此外,浏览器还会向 window.applicationCache 对象发送一个 checking 事件,在遵循合适的 HTTP 缓存规则前提下,获取清单文件。
  4. -
  5. 如果当前缓存的清单副本是最新的,浏览器将向 applicationCache 对象发送一个 noupdate 事件,到此,更新过程结束。注意,如果你在服务器修改了任何缓存资源,同时也应该修改清单文件,这样浏览器才能知道它需要重新获取资源。
  6. -
  7. 如果清单文件已经改变,文件中列出的所有文件—也包括通过调用 applicationCache.add() 方法添加到缓存中的那些文件—会被获取并放到一个临时缓存中,遵循适当的 HTTP 缓存规则。对于每个加入到临时缓存中的文件,浏览器会向 applicationCache 对象发送一个 progress 事件。如果出现任何错误,浏览器会发送一个 error 事件,并暂停更新。
  8. -
  9. 一旦所有文件都获取成功,它们会自动移送到真正的离线缓存中,并向  applicationCache 对象发送一个 cached 事件。鉴于文档早已经被从缓存加载到浏览器中,所以更新后的文档不会重新渲染,直到页面重新加载(可以手动或通过程序).
  10. -
- -

存储位置与清除离线缓存

- -

在 Chrome 中,你可以在设置中选择 「清除浏览器数据...」 或访问 chrome://appcache-internals/ 来清除缓存。Safari 在设置中有一个类似的"清空缓存" 选项,但是需要重启浏览器后才能生效。

- -

在 Firefox 中,离线缓存数据与 Firefox 配置文件是分开存储的—紧挨着硬盘缓存:

- - - -

在 Firefox 中可以通过访问 about:cache 页面(在「离线缓存设置」标题下)来检查离线缓存的当前状况。 若想单独清除每个网站的离线缓存,可以使用 工具 -> 选项 -> 高级 -> 网络 -> 离线数据中的「删除」按钮。

- -

在 Firefox 11 之前,无论是 工具 -> 清除近期历史 还是 工具 -> 选项 -> 高级 -> 网络 -> 离线数据 -> 立即清除 都无法清除离线缓存。这个问题已经被修复。(点击 “立即清除” 只是将缓存文件清除掉,并没将缓存清单删除,所以下次载入页面是更新缓存,而非创建缓存,意味着cached和updateready事件触发机制不同,如果想要清除掉缓存清单,只能选中域,然后点击移除)

- -

另请参阅 清除 DOM 存储数据

- -
-

应用缓存可以变成废弃的。如果从服务器上移除一个应用的清单文件,浏览器将会清除所有清单中列出的应用缓存,并向 applicationCache 对象发送一个「obsolete」事件。这将使得应用缓存的状态变为 OBSOLETE。

-
- -

缓存清单文件

- -

引用一个缓存清单文件

- -

web 应用中的 manifest 特性可以指定为缓存清单文件的相对路径或一个绝对 URL(绝对 URL 必须与应用同源)。缓存清单文件可以使用任意扩展名,但传输它的 MIME 类型必须为 text/cache-manifest。

- - - -
注意:在 Apache 服务器上,若要设置适用于清单(.appcache)文件的 MIME 类型,可以向根目录或应用的同级目录下的一个 .htaccess 文件中增加 AddType text/cache-manifest .appcache 。
- - - -

缓存清单文件中的记录

- -

缓存清单文件是一个纯文本文件,它列出了所有浏览器应该缓存起来的资源,以便能够离线访问。资源使用 URI 来标识。在缓存清单文件中列出的所有记录必须拥有相同的协议、主机名与端口号。

- -

示例 1:一个简单的缓存清单文件

- -
-

下面是一个简单的缓存清单文件,example.appcache,适用于一个虚拟的网站 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
-
- -

一个缓存清单文件可以包含三段内容 (CACHE, NETWORK, 和 FALLBACK, 下面详细讨论)。 在上面的例子中,没有段落标题,因此所有数据行都认为是属于显式 (CACHE) 段落,这意味着浏览器应该在应用缓存中缓存所有列出的资源。资源可以使用绝对或者相对 URL 来指定(例如 index.html)。

- -

上面例子中的注释 「v1」很有必要存在。只有当清单文件发生变化时,浏览器才会去更新应用缓存。如果你要更改缓存资源(比如说,你使用了一张新的 header.png 图片),你必须同时修改清单文件中的内容,以便让浏览器知道它们需要更新缓存。你可以对清单文件做任何改动,但大家都认同的最佳实践则是修正版本号。

- -
重要:不要在清单文件中指定清单文件本身,否则将无法让浏览器得知清单文件有新版本出现。
- -

缓存清单文件中的段落: CACHE, NETWORK,与 FALLBACK

- -

清单文件可以分为三段: CACHE, NETWORK,与 FALLBACK.

- -
-
CACHE:
-
这是缓存文件中记录所属的默认段落。在 CACHE段落标题后(或直接跟在 CACHE MANIFEST 行后)列出的文件会在它们第一次下载完毕后缓存起来。
-
NETWORK:
-
在 NETWORK: 段落标题下列出的文件是需要与服务器连接的白名单资源。所有类似资源的请求都会绕过缓存,即使用户处于离线状态。可以使用通配符。
-
FALLBACK:
-
FALLBACK: 段指定了一个后备页面,当资源无法访问时,浏览器会使用该页面。该段落的每条记录都列出两个 URI—第一个表示资源,第二个表示后备页面。两个 URI 都必须使用相对路径并且与清单文件同源。可以使用通配符。
-
- -

CACHE, NETWORK, 和 FALLBACK 段落可以以任意顺序出现在缓存清单文件中,并且每个段落可以在同一清单文件中出现多次。

- -

示例 2: 一个复杂且完整的缓存清单文件

- -

下面是一个更加完整的缓存清单文件,适用于一个虚拟的网站 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
-
- -

该例子使用了 NETWORK 与 FALLBACK 段落,指明了 network.html 页面必须始终从网络获取,fallback.html 页面应该作为后备资源来提供(例如,当无法与服务器建立连接时)。

- -

缓存清单文件的结构

- -

缓存清单文件必须以 text/cache-manifest MIME 类型来传输。所有通过 MIME 类型传输的文件必须符合本节中定义的适用于应用缓存清单的语法。

- -

缓存清单是 UTF-8 格式的文本文件,有可能包含一个 BOM 字符。新行可能使用换行符(U+000A),回车(U+000D),或回车加换行符来表示。

- -

缓存清单文件的第一行必须包含字符串 CACHE MANIFEST (两个单词间使用一个 U+0020 空白),紧接着是零或多个空白或制表符。本行的其他文本会被忽略。

- -

缓存清单文件的余下内容必须包含零或多个下面的行:

- -
-
空行
-
你可以使用包含零或多个空白与制表符的空行。
-
注释
-
注释包括零或多个制表符或空白字符,紧接着是一个 # 字符,再然后是零或多个注释文本字符。注释只能在所在行起作用,不能追加到其他行上。这意味着你无法使用片段标识符。
-
段落标题
-
段落标题指定了缓存文件即将操作的段落。有三个可选的标题:
-
- -
- - - - - - - - - - - - - - - - - - - -
段落标题解释
CACHE:切换到缓存清单的显式段落(默认段落)。
NETWORK:切换到缓存清单的在线白名单段落。
FALLBACK:切换到缓存清单的后备资源段落。
-
- -
-
段落标题所在的行可以包含空白字符,段落名后的冒号 (:) 不可省略。
-
段落数据
-
不同段落的数据行格式有所不同。在默认 (CACHE:) 段落,每行都是一个合法的  URI 或 IRI ,与一个要缓存的资源相关联(本段落内不允许通配符)。每行的 URI 或 IRI 前后允许出现空白字符。在 Fallback 段落内,每行都是一个合法的 URI 或 IRI(与一个资源关联),紧跟着一个后备资源,用于当无法与服务器建立连接时访问。在 Network 段落内,每行都是一个合法的 URI 或 IRI,关联一个需要通过网络获取的资源(本段落内可以使用通配符 *)。 -
注意:相对 URI 是指相对于缓存清单的 URI,而不是包含清单的文档的 URI。
-
-
- -

缓存清单可以在段落内任意切换(每个段落标题可以使用多次),而且段落允许为空。

- -

一个应用缓存中的资源

- -

一个应用缓存至少会包含一个资源,由 URI 指定。所有资源都属于下列类别之一:

- -
-
主记录
-
这些资源被加入缓存的原因是:用户浏览的一个上下文中包含一个文档,该文档用 manifest 特性明确指明了它属于该缓存。
-
显式记录
-
这些是在应用缓存清单文件中显式列出的资源。
-
网络记录
-
这些是在应用缓存清单文件中作为网络记录列出的资源。
-
后备记录
-
这些是在应用缓存清单文件中作为后备记录列出的资源。
-
- -
注意: 资源可以被标记为多个类别,因此可以作为多重记录来分类。例如,一条记录既可以是显式记录,也可以是一条后备记录。
- -

下面来详细介绍资源类别。

- -

主记录

-任意在 {{ HTMLElement("html") }} 元素上包含一个 {{ htmlattrxref("manifest","html") }} 特性的 HTML 文件都可以是主记录。例如,我们拥有 HTML 文件 http://www.example.com/entry.html,它看起来是这样的: - -
<html manifest="example.appcache">
-  <h1>Application Cache Example</h1>
-</html>
-
- -

如果 entry.html 没有在 example.appcache 缓存清单文件中列出来,那么访问 entry.html 页面会使得 entry.html 作为一条主记录加入到应用缓存中。

- -

显式记录

- -

显式记录就是在缓存清单文件的 CACHE 段落显式列出的资源

- -

网络记录

- -

缓存清单文件的 NETWORK 段落指定了 web 应用需要在线访问的资源。一个应用缓存中的网络记录本质上来说是一个「在线白名单」—在 NETWORK 段落指定的 URI 会从服务器而不是缓存加载。这使得浏览器的安全模型通过限制用户让其只访问经过验证的资源来避免潜在的安全漏洞。

- -

举例来说,你可以使用网络记录来从服务器而不是缓存中加载并执行脚本或其他代码:

- -
CACHE MANIFEST
-NETWORK:
-/api
-
- -

上面列出的缓存清单段落能够保证对 http://www.example.com/api/ 子目录中资源的请求始终通过网络加载,而不会去访问缓存。

- -
注意: 简单的从清单文件中过滤主记录(在 html 元素中拥有 manifest 特性的文件)并不会产生同样的结果,因为主记录会被添加到—后续访问的获取也会从—应用缓存中。
- -

后备记录

- -

当尝试请求资源失败时会使用后备记录。例如,缓存清单文件 http://www.example.com/example.appcache 包含如下内容:

- -
CACHE MANIFEST
-FALLBACK:
-example/bar/ example.html
-
- -

任何访问 http://www.example.com/example/bar/ 或它的任意子目录及内容都会使浏览器发出请求,去尝试加载请求的资源。如果尝试失败(可能是由于网络连接失败或服务器问题),浏览器将会加载 example.html。

- -

缓存状态

- -

每个应用缓存都有一个状态,标示着缓存的当前状况。共享同一清单 URI 的缓存拥有相同的缓存状态,可能是其中之一:

- -
-
UNCACHED(未缓存)
-
一个特殊的值,用于表明一个应用缓存对象还没有完全初始化。
-
IDLE(空闲)
-
应用缓存此时未处于更新过程中。
-
CHECKING(检查)
-
清单已经获取完毕并检查更新。
-
DOWNLOADING(下载中)
-
下载资源并准备加入到缓存中,这是由于清单变化引起的。
-
UPDATEREADY(更新就绪)
-
一个新版本的应用缓存可以使用。有一个对应的事件 updateready,当下载完毕一个更新,并且还未使用 swapCache() 方法激活更新时,该事件触发,而不会是 cached 事件。
-
OBSOLETE(废弃)
-
应用缓存现在被废弃。
-
- -

测试缓存清单的更新

- -

你可以使用 JavaScript 来写程序检测应用是否拥有一个可以更新的缓存清单文件。因为缓存清单文件可能会在脚本添加事件前完成更新,所以脚本应该始终检测 window.applicationCache.status。

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

 若要手动测试一个新的清单文件,你可以使用 window.applicationCache.update()。

- -

陷阱

- -
    -
  • 永远不要使用传统 GET 参数(例如 other-cached-page.html?parameterName=value) 来访问缓存文件。这会使浏览器绕过缓存,直接从网络获取。若想链接一个参数需要在 JavaScript 中解析的资源,你可以将参数放到链接的 hash 部分,例如 other-cached-page.html#whatever?parameterName=value。
  • -
  • 当应用被缓存后,仅仅更新在 web 页面中使用的资源(文件)还不足以更新被缓存的文件。你需要在浏览器获取和使用更新的文件前,去更新缓存清单文件本身。你可以使用 window.applicationCache.swapCache() 以编程的方式完成上述目的,虽然这无法影响到已经加载完毕的资源。为了保证资源从应用缓存的最新版本中加载,最理想的办法就是刷新页面
  • -
  • 通过在 web 服务器上设置 expires header 来使 *.appcache 文件立即过期是个好主意。这避免了将清单文件缓存的风险。例如,在 Apache 中,你可以指定下面的配置项:
    - ExpiresByType text/cache-manifest "access plus 0 seconds"
  • -
- -

浏览器兼容性

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support4.03.510.010.64.0
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown() }}{{ CompatNo() }}11.03.2
-
- -

注意:Firefox 3.5 之前的版本会忽略缓存清单文件中的 NETWORK 和 FALLBACK 段落。

- -

另见

- - - - -
-
diff --git a/files/zh-tw/web/html/using_the_application_cache/index.html b/files/zh-tw/web/html/using_the_application_cache/index.html deleted file mode 100644 index 660b5619a9..0000000000 --- a/files/zh-tw/web/html/using_the_application_cache/index.html +++ /dev/null @@ -1,391 +0,0 @@ ---- -title: Offline resources on Firefox -slug: Web/HTML/Using_the_application_cache -tags: - - Firefox 3 - - Offline web applications - - 待翻譯 -translation_of: Web/HTML/Using_the_application_cache ---- -
{{DefaultAPISidebar("App Cache")}}{{deprecated_header}}
- -
-

Using the application caching feature described here is at this point highly discouraged; it’s in the process of being removed from the Web platform. Use Service Workers instead. In fact as of Firefox 44, when AppCache is used to provide offline support for a page a warning message is now displayed in the console advising developers to use Service workers instead ({{bug("1204581")}}).

-
- -

Introduction

- -

HTML5 provides an application caching mechanism that lets web-based applications run offline. Developers can use the Application Cache (AppCache) interface to specify resources that the browser should cache and make available to offline users. Applications that are cached load and work correctly even if users click the refresh button when they are offline.

- -

Using an application cache gives an application the following benefits:

- - - -

How the application cache works

- -

Enabling the application cache

- -

To enable the application cache for an application, you must include the {{htmlattrxref("manifest", "html")}} attribute in the {{HTMLElement("html")}} element in your application's pages, as shown in the following example:

- -
<html manifest="example.appcache">
-  ...
-</html>
-
- -

The manifest attribute references a cache manifest file, which is a text file that lists resources (files) that the browser should cache for your application.

- -

You should include the manifest attribute on every page of your application that you want cached. The browser does not cache pages that do not contain the manifest attribute, unless such pages are explicitly listed in the manifest file itself. You do not need to list all the pages you want cached in the manifest file, the browser implicitly adds every page that the user visits and that has the manifest attribute set to the application cache.

- -

Some browsers (e.g., Firefox) display a notification bar the first time a user loads an application that uses the application cache. The notification bar displays a message such as:

- -

This website (www.example.com) is asking to store data on your computer for offline use. [Allow] [Never for This Site] [Not Now]

- -

The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities.

- -

Loading documents

- -

The use of an application cache modifies the normal process of loading a document:

- - - -

The process for loading documents and updating the application cache is specified in greater detail below:

- -
    -
  1. When the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and then fetches all the entries listed in the manifest file, creating the first version of the application cache.
  2. -
  3. Subsequent visits to that document cause the browser to load the document and other assets specified in the manifest file from the application cache (not from the server). In addition, the browser also sends a checking event to the window.applicationCache object, and fetches the manifest file, following the appropriate HTTP caching rules.
  4. -
  5. If the currently-cached copy of the manifest is up-to-date, the browser sends a noupdate event to the applicationCache object, and the update process is complete. Note that if you change any cached resources on the server, you must also change the manifest file itself, so that the browser knows it needs to fetch all the resources again.
  6. -
  7. If the manifest file has changed, all the files listed in the manifest—as well as those added to the cache by calling applicationCache.add()—are fetched into a temporary cache, following the appropriate HTTP caching rules. For each file fetched into this temporary cache, the browser sends a progress event to the applicationCache object. If any errors occur, the browser sends an error event, and the update halts.
  8. -
  9. Once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a cached event is sent to the applicationCache object. Since the document has already been loaded into the browser from the cache, the updated document will not be rendered until the document is reloaded (either manually or programatically).
  10. -
- -

Storage location and clearing the offline cache

- -

In Chrome you can clear the offline cache by selecting "Clear browsing data..." in the preferences or by visiting chrome://appcache-internals/. Safari has a similar "Empty cache" setting in its preferences but a browser restart may also be required.

- -

In Firefox, the offline cache data is stored separately from the Firefox profile—next to the regular disk cache:

- - - -

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.

- -

On Linux, you can find the setting at Edit > Preferences > Advanced > Network > Offline Web Content and User Data

- -

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 (CACHE, NETWORK, 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: CACHE, NETWORK, and FALLBACK

- -

A manifest can have three distinct sections: CACHE, NETWORK, 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. The wildcard character * can be used once. Most sites need *.
-
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 CACHE, NETWORK, 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 (after the initial CACHE MANIFEST line), 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 headerDescription
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 (or the wildcard character * can be used 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() {
-  console.log('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

- - - -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support4.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}[1]10.010.64.0
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0.1[2]11.0[3]11.03.2
-
- -

[1] Versions of Firefox prior to 3.5 ignore the NETWORK and FALLBACK sections of the cache manifest file.

- -

[2] When using AppCache to provide Firefox OS hosted apps with offline capabilities, you need to declare the AppCache manifest inside your Firefox OS manifest.webapp file's appcache_path field.

- -

[3] Reloading the page in IE Mobile will clear the application cache, so the webpage will fail to load. However, closing the page and opening via bookmark again works fine.

- -

See also

- - -- cgit v1.2.3-54-g00ecf From c0c29873129622b08cce7c367f855698765f6687 Mon Sep 17 00:00:00 2001 From: julieng Date: Mon, 12 Apr 2021 07:41:48 +0200 Subject: fixing redirects with yarn content --- files/de/_redirects.txt | 6 +++++- files/es/_redirects.txt | 7 +++++-- files/fr/_redirects.txt | 3 --- files/it/_redirects.txt | 7 +++++-- files/ja/_redirects.txt | 8 +++++--- files/ko/_redirects.txt | 6 +++++- files/pt-br/_redirects.txt | 1 - files/pt-pt/_redirects.txt | 6 +++++- files/ru/_redirects.txt | 2 -- files/zh-cn/_redirects.txt | 1 - files/zh-tw/_redirects.txt | 7 +++++-- 11 files changed, 35 insertions(+), 19 deletions(-) (limited to 'files') diff --git a/files/de/_redirects.txt b/files/de/_redirects.txt index edfd74c3af..09b93b3899 100644 --- a/files/de/_redirects.txt +++ b/files/de/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /de/docs/AJAX /de/docs/Web/Guide/AJAX /de/docs/Apps/Progressiv /de/docs/Web/Progressive_web_apps @@ -297,7 +302,6 @@ /de/docs/HTML/HTML5/HTML5_element_list /de/docs/conflicting/Web/HTML/Element /de/docs/HTML/HTML5/liste_der_HTML5_elemente /de/docs/conflicting/Web/HTML/Element /de/docs/HTML/Inline_elemente /de/docs/Web/HTML/Inline_elements -/de/docs/HTML/Using_the_application_cache /de/docs/Web/HTML/Using_the_application_cache /de/docs/HTML:Element /de/docs/Web/HTML/Element /de/docs/HTML:Element:b /de/docs/Web/HTML/Element/b /de/docs/HTML:Element:h1 /de/docs/Web/HTML/Element/Heading_Elements diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 5edb9ac27f..00ecdbc826 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /es/docs/AJAX /es/docs/Web/Guide/AJAX /es/docs/AJAX/Comunidad /es/docs/Web/Guide/AJAX/Community @@ -1438,7 +1443,6 @@ /es/docs/Principios_básicos_de_los_servicios_Web /es/docs/orphaned/Principios_básicos_de_los_servicios_Web /es/docs/Quirks_Mode_and_Standards_Mode /es/docs/Web/HTML/Quirks_Mode_and_Standards_Mode /es/docs/Recursos_en_modo_desconectado_en_Firefox /es/docs/orphaned/Recursos_en_modo_desconectado_en_Firefox -/es/docs/Recursos_offline_en_firefox /es/docs/Web/HTML/Using_the_application_cache /es/docs/Referencia_CSS /es/docs/Web/CSS/Reference /es/docs/Referencia_CSS/Extensiones_CSS_Mozilla /es/docs/Web/CSS/Mozilla_Extensions /es/docs/Referencia_CSS/Extensiones_Mozilla /es/docs/Web/CSS/Mozilla_Extensions @@ -2252,7 +2256,6 @@ /es/docs/Web/HTML/La_importancia_de_comentar_correctamente /es/docs/conflicting/Learn/HTML/Introduction_to_HTML/Getting_started /es/docs/Web/HTML/Microdatos /es/docs/Web/HTML/Microdata /es/docs/Web/HTML/Optimizing_your_pages_for_speculative_parsing /es/docs/Glossary/speculative_parsing -/es/docs/Web/HTML/Recursos_offline_en_firefox /es/docs/Web/HTML/Using_the_application_cache /es/docs/Web/HTML/Referencia /es/docs/Web/HTML/Reference /es/docs/Web/HTML/Tipos_de_enlaces /es/docs/Web/HTML/Link_types /es/docs/Web/HTML/Transision_adaptativa_DASH /es/docs/Web/Media/DASH_Adaptive_Streaming_for_HTML_5_Video diff --git a/files/fr/_redirects.txt b/files/fr/_redirects.txt index 7ec0778167..f956671d39 100644 --- a/files/fr/_redirects.txt +++ b/files/fr/_redirects.txt @@ -3464,7 +3464,6 @@ /fr/docs/Précis_CSS_2/Tout_en_un /fr/docs/Web/CSS/Reference /fr/docs/Précis_CSS_2:Tout_en_un /fr/docs/Web/CSS/Reference /fr/docs/Qualité /fr/docs/QA -/fr/docs/Ressources_hors_ligne_dans_Firefox /fr/docs/Web/HTML/Using_the_application_cache /fr/docs/Référence_DOM_Gecko /fr/docs/conflicting/Glossary/DOM /fr/docs/Référence_de_JavaScript_1.5_Core /fr/docs/Web/JavaScript/Reference /fr/docs/Référence_de_JavaScript_1.5_Core/A_propos_de_cette_reference /fr/docs/Web/JavaScript/Reference/About @@ -3590,7 +3589,6 @@ /fr/docs/Utilisation_du_DOM_Level_1_Core_du_W3C/Exemple /fr/docs/Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core/Example /fr/docs/Utilisation_du_cache_dans_Firefox_1.5 /fr/docs/Mozilla/Firefox/Releases/1.5/Using_Firefox_1.5_caching /fr/docs/Utilisation_du_cache_de_Firefox_1.5 /fr/docs/Mozilla/Firefox/Releases/1.5/Using_Firefox_1.5_caching -/fr/docs/Utiliser_Application_Cache /fr/docs/Web/HTML/Using_the_application_cache /fr/docs/Web/API/API_HTML_Drag_and_Drop /fr/docs/Web/API/HTML_Drag_and_Drop_API /fr/docs/Web/API/API_HTML_Drag_and_Drop/Opérations_de_glissement /fr/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations /fr/docs/Web/API/API_IndexedDB /fr/docs/Web/API/IndexedDB_API @@ -4546,7 +4544,6 @@ /fr/docs/Web/HTML/Sections_and_Outlines_of_an_HTML5_document /fr/docs/Web/Guide/HTML/Using_HTML_sections_and_outlines /fr/docs/Web/HTML/Types_de_lien /fr/docs/Web/HTML/Link_types /fr/docs/Web/HTML/Utilisation_d'audio_et_video_en_HTML5 /fr/docs/conflicting/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content_040b1c36f4218ba488ffb0284dfe52bf -/fr/docs/Web/HTML/Utiliser_Application_Cache /fr/docs/Web/HTML/Using_the_application_cache /fr/docs/Web/HTML/Utiliser_DASH_avec_les_vidéos_en_HTML /fr/docs/Web/Media/DASH_Adaptive_Streaming_for_HTML_5_Video /fr/docs/Web/HTML/formats_media_support /fr/docs/Web/Media/Formats /fr/docs/Web/HTML/Éléments_en_bloc /fr/docs/Web/HTML/Block-level_elements diff --git a/files/it/_redirects.txt b/files/it/_redirects.txt index 8845650b84..fb151fd05a 100644 --- a/files/it/_redirects.txt +++ b/files/it/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /it/docs/AJAX /it/docs/Web/Guide/AJAX /it/docs/AJAX/Iniziare /it/docs/Web/Guide/AJAX/Getting_Started @@ -388,7 +393,6 @@ /it/docs/HTML/HTML5/Introduction_to_HTML5 /it/docs/Web/Guide/HTML/HTML5/Introduction_to_HTML5 /it/docs/HTML/Introduzione /it/docs/Learn/HTML/Introduction_to_HTML /it/docs/HTML/Sections_and_Outlines_of_an_HTML5_document /it/docs/Web/Guide/HTML/Using_HTML_sections_and_outlines -/it/docs/HTML/utilizzare_application_cache /it/docs/Web/HTML/Using_the_application_cache /it/docs/Il_DOM_e_JavaScript /it/docs/Web/JavaScript/JavaScript_technologies_overview /it/docs/Importare_applicazioni_da_Internet_Explorer_a_Mozilla /it/docs/Migrare_applicazioni_da_Internet_Explorer_a_Mozilla /it/docs/Indentazione_corretta_delle_liste /it/docs/Web/CSS/CSS_Lists_and_Counters/Consistent_list_indentation @@ -559,7 +563,6 @@ /it/docs/Web/HTML/HTML5/Introduction_to_HTML5 /it/docs/Web/Guide/HTML/HTML5/Introduction_to_HTML5 /it/docs/Web/HTML/Riferimento /it/docs/Web/HTML/Reference /it/docs/Web/HTML/Sections_and_Outlines_of_an_HTML5_document /it/docs/Web/Guide/HTML/Using_HTML_sections_and_outlines -/it/docs/Web/HTML/utilizzare_application_cache /it/docs/Web/HTML/Using_the_application_cache /it/docs/Web/HTTP/Basi_HTTP /it/docs/Web/HTTP/Basics_of_HTTP /it/docs/Web/HTTP/Compressione /it/docs/Web/HTTP/Compression /it/docs/Web/HTTP/Panoramica /it/docs/Web/HTTP/Overview diff --git a/files/ja/_redirects.txt b/files/ja/_redirects.txt index 8e4caba570..8e454ee1ea 100644 --- a/files/ja/_redirects.txt +++ b/files/ja/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /ja/docs/AJAX /ja/docs/Web/Guide/AJAX /ja/docs/AJAX/Community /ja/docs/Web/Guide/AJAX/Community @@ -2578,7 +2583,6 @@ /ja/docs/HTML/Supported_media_formats /ja/docs/Web/Media/Formats /ja/docs/HTML/Tips_for_authoring_fast-loading_HTML_pages /ja/docs/conflicting/Learn/HTML/Howto/Author_fast-loading_HTML_pages /ja/docs/HTML/Using_HTML5_audio_and_video /ja/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content -/ja/docs/HTML/Using_the_application_cache /ja/docs/Web/HTML/Using_the_application_cache /ja/docs/HTML/属性 /ja/docs/Web/HTML/Attributes /ja/docs/HTML:Block-level_elements /ja/docs/Web/HTML/Block-level_elements /ja/docs/HTML:Canvas /ja/docs/Web/API/Canvas_API @@ -3439,7 +3443,6 @@ /ja/docs/Notification_object/tag /ja/docs/Web/API/Notification/tag /ja/docs/Notification_object/title /ja/docs/Web/API/Notification/title /ja/docs/NsIDOMHTMLMediaElement /ja/docs/orphaned/NsIDOMHTMLMediaElement -/ja/docs/Offline_resources_in_Firefox /ja/docs/Web/HTML/Using_the_application_cache /ja/docs/Offline_resources_in_Firefox/Using_audio_and_video_in_Firefox /ja/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content /ja/docs/Online_and_offline_events /ja/docs/Web/API/NavigatorOnLine/Online_and_offline_events /ja/docs/Other_JavaScript_tools /ja/docs/Tools @@ -3643,7 +3646,6 @@ /ja/docs/Updating_extensions_for_Firefox_3.1 /ja/docs/Mozilla/Firefox/Releases/3.5/Updating_extensions /ja/docs/Updating_web_applications_for_Firefox_3 /ja/docs/Mozilla/Firefox/Releases/3/Updating_web_applications /ja/docs/User_Agent_Strings_Reference /ja/docs/conflicting/Web/HTTP/Headers/User-Agent/Firefox -/ja/docs/Using_Application_Cache /ja/docs/Web/HTML/Using_the_application_cache /ja/docs/Using_Breakpoints_in_Venkman-redirect-1 /ja/docs/Using_Breakpoints_in_Venkman /ja/docs/Using_Firefox_1.5_caching /ja/docs/Mozilla/Firefox/Releases/1.5/Using_Firefox_1.5_caching /ja/docs/Using_HTML5_audio_and_video /ja/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content diff --git a/files/ko/_redirects.txt b/files/ko/_redirects.txt index 92b8107451..c3d8339b2d 100644 --- a/files/ko/_redirects.txt +++ b/files/ko/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /ko/docs/AJAX /ko/docs/Web/Guide/AJAX /ko/docs/AJAX/Getting_Started /ko/docs/Web/Guide/AJAX/Getting_Started @@ -325,7 +330,6 @@ /ko/docs/HTML/HTML에서_폼 /ko/docs/Learn/Forms /ko/docs/HTML/Inline_elements /ko/docs/Web/HTML/Inline_elements /ko/docs/HTML/Introduction /ko/docs/Learn/HTML/Introduction_to_HTML -/ko/docs/HTML/Using_the_application_cache /ko/docs/Web/HTML/Using_the_application_cache /ko/docs/HTML:Canvas /ko/docs/Web/API/Canvas_API /ko/docs/HTML:Element /ko/docs/Web/HTML/Element /ko/docs/HTML:Element:a /ko/docs/Web/HTML/Element/a diff --git a/files/pt-br/_redirects.txt b/files/pt-br/_redirects.txt index b97490c78e..43c76308bd 100644 --- a/files/pt-br/_redirects.txt +++ b/files/pt-br/_redirects.txt @@ -346,7 +346,6 @@ /pt-BR/docs/HTML/Introducao /pt-BR/docs/Learn/HTML/Introduction_to_HTML /pt-BR/docs/HTML/Introduction /pt-BR/docs/Learn/HTML/Introduction_to_HTML /pt-BR/docs/HTML/Optimizing_Your_Pages_for_Speculative_Parsing /pt-BR/docs/Glossary/speculative_parsing -/pt-BR/docs/HTML/Using_the_application_cache /pt-BR/docs/Web/HTML/Using_the_application_cache /pt-BR/docs/Hello_World_Rust /pt-BR/docs/orphaned/Hello_World_Rust /pt-BR/docs/IndexedDB /pt-BR/docs/Web/API/IndexedDB_API /pt-BR/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /pt-BR/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB diff --git a/files/pt-pt/_redirects.txt b/files/pt-pt/_redirects.txt index 5f775f9c9c..5ae20c7836 100644 --- a/files/pt-pt/_redirects.txt +++ b/files/pt-pt/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /pt-PT/docs/AJAX /pt-PT/docs/Web/Guide/AJAX /pt-PT/docs/AJAX/Como_começar /pt-PT/docs/Web/Guide/AJAX/Getting_Started @@ -954,7 +959,6 @@ /pt-PT/docs/Web/HTML/HTML5/Parser_HTML5 /pt-PT/docs/Web/Guide/HTML/HTML5/HTML5_Parser /pt-PT/docs/Web/HTML/Referencia /pt-PT/docs/Web/HTML/Reference /pt-PT/docs/Web/HTML/Tipos_de_hiperligacao /pt-PT/docs/Web/HTML/Link_types -/pt-PT/docs/Web/HTML/Utilizar_a_cache_de_aplicacao /pt-PT/docs/Web/HTML/Using_the_application_cache /pt-PT/docs/Web/HTML_Linguagem_de_marcacao_de_hipertexto /pt-PT/docs/Web/HTML /pt-PT/docs/Web/JavaScript/Estruturas_de_dados /pt-PT/docs/Web/JavaScript/Data_structures /pt-PT/docs/Web/JavaScript/Gestao_Memoria /pt-PT/docs/Web/JavaScript/Memory_Management diff --git a/files/ru/_redirects.txt b/files/ru/_redirects.txt index 945dd2fd9d..ca9db1d561 100644 --- a/files/ru/_redirects.txt +++ b/files/ru/_redirects.txt @@ -115,7 +115,6 @@ /ru/docs/HTML/HTML5/Constraint_validation /ru/docs/Web/Guide/HTML/HTML5/Constraint_validation /ru/docs/HTML/HTML5/Введение_в_HTML5 /ru/docs/Web/Guide/HTML/HTML5/Introduction_to_HTML5 /ru/docs/HTML/Optimizing_Your_Pages_for_Speculative_Parsing /ru/docs/Glossary/speculative_parsing -/ru/docs/HTML/Использование_кэширования_приложений /ru/docs/Web/HTML/Using_the_application_cache /ru/docs/IndexedDB /ru/docs/Web/API/IndexedDB_API /ru/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB /ru/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /ru/docs/IndexedDB/Using_IndexedDB /ru/docs/Web/API/IndexedDB_API/Using_IndexedDB @@ -624,7 +623,6 @@ /ru/docs/Web/HTML/Global_attributes/dropzone /ru/docs/orphaned/Web/HTML/Global_attributes/dropzone /ru/docs/Web/HTML/Optimizing_Your_Pages_for_Speculative_Parsing /ru/docs/Glossary/speculative_parsing /ru/docs/Web/HTML/Использование_HTML5_audio_и_video /ru/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content -/ru/docs/Web/HTML/Использование_кэширования_приложений /ru/docs/Web/HTML/Using_the_application_cache /ru/docs/Web/HTML/Общие_атрибуты /ru/docs/Web/HTML/Global_attributes /ru/docs/Web/HTML/Общие_атрибуты/accesskey /ru/docs/Web/HTML/Global_attributes/accesskey /ru/docs/Web/HTML/Общие_атрибуты/class /ru/docs/Web/HTML/Global_attributes/class diff --git a/files/zh-cn/_redirects.txt b/files/zh-cn/_redirects.txt index c22f490a05..c892700c59 100644 --- a/files/zh-cn/_redirects.txt +++ b/files/zh-cn/_redirects.txt @@ -705,7 +705,6 @@ /zh-CN/docs/HTML/HTML_Elements /zh-CN/docs/Web/HTML/Element/Heading_Elements /zh-CN/docs/HTML/HTML_Elements/time /zh-CN/docs/Web/HTML/Element/time /zh-CN/docs/HTML/Introduction /zh-CN/docs/learn/HTML/Introduction_to_HTML -/zh-CN/docs/HTML/Using_the_application_cache /zh-CN/docs/Web/HTML/Using_the_application_cache /zh-CN/docs/HTML/块级元素 /zh-CN/docs/Web/HTML/Block-level_elements /zh-CN/docs/HTML\Canvas\Tutorial /zh-CN/docs/Web/API/Canvas_API/Tutorial /zh-CN/docs/HTTP /zh-CN/docs/Web/HTTP diff --git a/files/zh-tw/_redirects.txt b/files/zh-tw/_redirects.txt index b718566c0d..580f746e41 100644 --- a/files/zh-tw/_redirects.txt +++ b/files/zh-tw/_redirects.txt @@ -1,3 +1,8 @@ +# DO NOT EDIT THIS FILE MANUALLY. +# Use the CLI instead: +# +# yarn content add-redirect +# # FROM-URL TO-URL /zh-TW/docs/AJAX /zh-TW/docs/Web/Guide/AJAX /zh-TW/docs/AJAX/Getting_Started /zh-TW/docs/Web/Guide/AJAX/Getting_Started @@ -518,7 +523,6 @@ /zh-TW/docs/Mozilla/Firefox/Releases/4/Firefox_4_開發者新功能概覽 /zh-TW/docs/orphaned/Mozilla/Firefox/Releases/4/Firefox_4_開發者新功能概覽 /zh-TW/docs/Mozilla_event_reference /zh-TW/docs/Web/Events /zh-TW/docs/Mozilla_event_reference/DOMContentLoaded_(event) /zh-TW/docs/Web/API/Window/DOMContentLoaded_event -/zh-TW/docs/Offline_resources_on_Firefox /zh-TW/docs/Web/HTML/Using_the_application_cache /zh-TW/docs/Prism:主視窗 /zh-TW/docs/Prism/主視窗 /zh-TW/docs/Prism:安裝程式 /zh-TW/docs/Prism/安裝程式 /zh-TW/docs/Python /zh-TW/docs/conflicting/Learn/Server-side/Django @@ -664,7 +668,6 @@ /zh-TW/docs/Web/HTML/HTML5/Introduction_to_HTML5 /zh-TW/docs/Web/Guide/HTML/HTML5/Introduction_to_HTML5 /zh-TW/docs/Web/HTML/HTML5_表單 /zh-TW/docs/Learn/Forms /zh-TW/docs/Web/HTML/Introduction /zh-CN/docs/learn/HTML/Introduction_to_HTML -/zh-TW/docs/Web/HTML/Offline_resources_on_Firefox /zh-TW/docs/Web/HTML/Using_the_application_cache /zh-TW/docs/Web/HTML/Supported_media_formats /zh-TW/docs/conflicting/Web/Media/Formats /zh-TW/docs/Web/HTML/區塊級元素 /zh-TW/docs/Web/HTML/Block-level_elements /zh-TW/docs/Web/HTTP/Access_control_CORS /zh-TW/docs/Web/HTTP/CORS -- cgit v1.2.3-54-g00ecf