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

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

В 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 header Description
CACHE: Switches to the explicit section of the cache manifest (this is the default section).
NETWORK: Switches to the online whitelist section of the cache manifest.
FALLBACK: Switches to the fallback section of the cache manifest.
The section header line may include whitespaces, but must include the colon (:) in the section name.
Section data
The format for lines of data varies from section to section. In the explicit (CACHE:) section, each line is a valid URI or IRI reference to a resource to cache (no wildcard characters are allowed in this sections). Whitespace is allowed before and after the URI or IRI on each line. In the Fallback section each line is a valid URI or IRI reference to a resource, followed by a fallback resource that is to be served up when a connection with the server cannot be made. In the network section, each line is a valid URI or IRI reference to a resource to fetch from the network (the wildcard character * is allowed in this section).
Note: Relative URIs are relative to the cache manifest's URI, not to the URI of the document referencing the manifest.

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

Resources in an application cache

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

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

Resource categories are described in greater detail below.

Master entries

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

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

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

Explicit entries

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

Network entries

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

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

CACHE MANIFEST
NETWORK:
/api

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

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

Fallback entries

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

CACHE MANIFEST
FALLBACK:
example/bar/ example.html

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

Cache states

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

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

Testing for updates to the cache manifest

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

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

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

Gotchas

Browser compatibility

{{CompatibilityTable}}

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

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

See also