diff options
author | julieng <julien.gattelier@gmail.com> | 2021-04-11 16:03:26 +0200 |
---|---|---|
committer | julieng <julien.gattelier@gmail.com> | 2021-04-11 16:03:26 +0200 |
commit | 25debec66a35fc20db84bf5aca690489b5bec306 (patch) | |
tree | 7bbcf81f9d88ebac8678dfe42aaae89420735c8f | |
parent | 65d95ceeaf294384181454b9cf73c70319c2e563 (diff) | |
download | translated-content-25debec66a35fc20db84bf5aca690489b5bec306.tar.gz translated-content-25debec66a35fc20db84bf5aca690489b5bec306.tar.bz2 translated-content-25debec66a35fc20db84bf5aca690489b5bec306.zip |
Archiving HTML - Using the Application cache
11 files changed, 0 insertions, 4025 deletions
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 ---- -<h2 id="Einführung">Einführung</h2> - -<p><a href="/de/docs/Web/HTML/HTML5" title="HTML/HTML5">HTML5</a> bietet einen <em>Anwendungscaching</em>-Mechanismus, welcher webbasierte Anwendungen offline nutzbar macht. Entwickler können das <strong>Application Cache</strong> (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.</p> - -<p>Die Nutzung des Application Cache ermöglicht einer Anwendung folgende Vorteile: </p> - -<ul> - <li>Offline surfen: Nutzer können durch eine Seite navigieren wenn sie offline sind.</li> - <li>Geschwindigkeit: Gecachte Ressourcen sind lokal und laden daher schneller.</li> - <li>Verminderte Serverlast: Der Browser lädt nur die Ressourcen vom Server, die sich geändert haben.</li> -</ul> - -<h2 id="Wie_der_AppCache_funktioniert">Wie der AppCache funktioniert</h2> - -<h3 id="Aktivieren_des_AppCaches">Aktivieren des AppCaches</h3> - -<p>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:</p> - -<div style="overflow: hidden;"> -<pre class="brush: html"><html manifest="example.appcache"> - ... -</html> -</pre> -</div> - -<p>Das Manifest-Attribut verweist auf eine <strong>cache manifest</strong>-Datei, die als Textdatei alle Ressourcen (Dateien) auflistet, die der Browser innerhalb der App cachen soll.</p> - -<p>Sie sollten das <code>manifest</code>-Attribute auf jeder Seite Ihrer App einbinden, die zwischengespeichert werden soll. Der Browser speichert keine Seiten die nicht das <code>manifest</code>-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 <code>manifest</code>-Attribute enthalten.</p> - -<p>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:</p> - -<p style="margin-left: 40px;">Die Webseite (<code>www.example.com</code>) möchte gerne Daten zur Offline-Benutzung abspeichern. [Erlauben] [Nie für diese Seite] [Nicht jetzt]</p> - -<p>The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities.</p> - -<h3 id="Loading_documents">Loading documents</h3> - -<p>The use of an application cache modifies the normal process of loading a document:</p> - -<ul> - <li>If an application cache exists, the browser loads the document and its associated resources directly from the cache, without accessing the network. This speeds up the document load time.</li> - <li>The browser then checks to see if the cache manifest has been updated on the server.</li> - <li>If the cache manifest has been updated, the browser downloads a new version of the manifest and the resources listed in the manifest. This is done in the background and does not affect performance significantly.</li> -</ul> - -<p>The process for loading documents and updating the application cache is specified in greater detail below:</p> - -<ol> - <li>When the browser visits a document that includes the <code>manifest</code> 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.</li> - <li>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 <code>checking</code> event to the <code><a href="/en-US/docs/DOM/window.applicationCache" title="DOM/window.applicationCache">window.applicationCache</a></code> object, and fetches the manifest file, following the appropriate HTTP caching rules.</li> - <li>If the currently-cached copy of the manifest is up-to-date, the browser sends a <code>noupdate</code> event to the <code>applicationCache</code> 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.</li> - <li>If the manifest file <em>has</em> changed, all the files listed in the manifest—as well as those added to the cache by calling <code><a href="/en-US/docs/nsIDOMOfflineResourceList#add.28.29" title="nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a></code>—are fetched into a temporary cache, following the appropriate HTTP caching rules. For each file fetched into this temporary cache, the browser sends a <code>progress</code> event to the <code>applicationCache</code> object. If any errors occur, the browser sends an <code>error</code> event, and the update halts.</li> - <li>Once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a <code>cached</code> event is sent to the <code>applicationCache</code> 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).</li> -</ol> - -<h2 id="Storage_location_and_clearing_the_offline_cache">Storage location and clearing the offline cache</h2> - -<p>In Chrome you can clear the offline cache by selecting "Clear browsing data..." in the preferences or by visiting <a title="chrome://appcache-internals/">chrome://appcache-internals/</a>. Safari has a similar "Empty cache" setting in its preferences but a browser restart may also be required.</p> - -<p>In Firefox, the offline cache data is stored separately from the Firefox profile—next to the regular disk cache:</p> - -<ul> - <li>Windows Vista/7: <code>C:\Users\<username>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache</code></li> - <li>Mac/Linux: <code>/Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache</code></li> -</ul> - -<p>In Firefox the current status of the offline cache can be inspected on the <code>about:cache</code> page (under the "Offline cache device" heading). The offline cache can be cleared for each site separately using the "Remove..." button in Tools -> Options -> Advanced -> Network -> Offline data.</p> - -<p>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.</p> - -<p>See also <a href="/en-US/docs/DOM/Storage#Storage_location_and_clearing_the_data" title="DOM/Storage#Storage location and clearing the data">clearing the DOM Storage data</a>.</p> - -<p>Application caches can also become obsolete. If an application's manifest file is removed from the server, the browser removes all application caches that use that manifest, and sends an "obsolete" event to the <code>applicationCache</code> object. This sets the application cache's state to <code>OBSOLETE</code>.</p> - -<h2 id="The_cache_manifest_file">The cache manifest file</h2> - -<h3 id="Referencing_a_cache_manifest_file">Referencing a cache manifest file</h3> - -<p>The <code>manifest</code> 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 <code>text/cache-manifest</code>.</p> - -<div class="note"><strong>Note: </strong>On Apache servers, the MIME type for manifest (.appcache) files can be set by adding <code>AddType text/cache-manifest .appcache</code> to a .htaccess file within either the root directory, or the same directory as the application.</div> - -<h3 id="Entries_in_a_cache_manifest_file">Entries in a cache manifest file</h3> - -<p>The cache manifest file is a simple text file that lists the resources the browser should cache for offline access. Resources are identified by URI. Entries listed in the cache manifest must have the same scheme, host, and port as the manifest.</p> - -<h3 id="Example_1_a_simple_cache_manifest_file">Example 1: a simple cache manifest file</h3> - -<p>The following is a simple cache manifest file, <code>example.appcache</code>, for an imaginary web site at <span class="nowiki">www.example.com</span>.</p> - -<pre>CACHE MANIFEST -# v1 - 2011-08-13 -# This is a comment. -<span class="nowiki">http://www.example.com/index.html</span> -<span class="nowiki">http://www.example.com/header.png</span> -<span class="nowiki">http://www.example.com/blah/blah</span> -</pre> - -<p>A cache manifest file can include three sections (<code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>, discussed below). In the example above, there is no section header, so all data lines are assumed to be in the explicit (<code>CACHE</code>) section, meaning that the browser should cache all the listed resources in the application cache. Resources can be specified using either absolute or relative URLs (e.g., <code>index.html</code>).</p> - -<p>The "v1" comment in the example above is there for a good reason. Browsers only update an application cache when the manifest file changes, byte for byte. If you change a cached resource (for example, you update the <code>header.png</code> image with new content), you must also change the content of the manifest file in order to let browsers know that they need to refresh the cache. You can make any change you want to the manifest file, but revising a version number is the recommended best practice.</p> - -<div class="warning"><strong>Important:</strong> Do not specify the manifest itself in the cache manifest file, otherwise it will be nearly impossible to inform the browser a new manifest is available.</div> - -<h3 id="Sections_in_a_cache_manifest_file_CACHE_NETWORK_and_FALLBACK">Sections in a cache manifest file: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code></h3> - -<p>A manifest can have three distinct sections: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>.</p> - -<dl> - <dt><code>CACHE:</code></dt> - <dd>This is the default section for entries in a cache manifest file. Files listed under the <code>CACHE:</code> section header (or immediately after the <code>CACHE MANIFEST</code> line) are explicitly cached after they're downloaded for the first time.</dd> - <dt><code>NETWORK:</code></dt> - <dd>Files listed under the <code>NETWORK:</code> section header in the cache manifest file are white-listed resources that require a connection to the server. All requests to such resources bypass the cache, even if the user is offline. Wildcards may be used.</dd> - <dt><code>FALLBACK:</code></dt> - <dd>The <code>FALLBACK:</code> section specifies fallback pages the browser should use if a resource is inaccessible. Each entry in this section lists two URIs—the first is the resource, the second is the fallback. Both URIs must be relative and from the same origin as the manifest file. Wildcards may be used.</dd> -</dl> - -<p>The <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK </code>sections can be listed in any order in a cache manifest file, and each section can appear more than once in a single manifest.</p> - -<h3 id="Example_2_a_more_complete_cache_manifest_file">Example 2: a more complete cache manifest file</h3> - -<p>The following is a more complete cache manifest file for the imaginary web site at <span class="nowiki">www.example.com</span>:</p> - -<pre>CACHE MANIFEST -# v1 2011-08-14 -# This is another comment -index.html -cache.html -style.css -image1.png - -# Use from network if available -NETWORK: -network.html - -# Fallback content -FALLBACK: -/ fallback.html -</pre> - -<p>This example uses <code>NETWORK</code> and <code>FALLBACK</code> sections to specify that the <code>network.html</code> page must always be retrieved from the network, and that the <code>fallback.html</code> page should be served as a fallback resource (e.g., in case a connection to the server cannot be established).</p> - -<h3 id="Structure_of_a_cache_manifest_file">Structure of a cache manifest file</h3> - -<p>Cache manifest files must be served with the <code>text/cache-manifest</code> MIME type. All resources served using this MIME type must follow the syntax for an application cache manifest, as defined in this section.</p> - -<p>Cache manifests are UTF-8 format text files, and may optionally include a BOM character. Newlines may be represented by line feed (<code>U+000A</code>), carriage return (<code>U+000D</code>), or carriage return and line feed both.</p> - -<p>The first line of the cache manifest must consist of the string <code>CACHE MANIFEST</code> (with a single <code>U+0020</code> space between the two words), followed by zero or more space or tab characters. Any other text on the line is ignored.</p> - -<p>The remainder of the cache manifest must be comprised of zero or more of the following lines:</p> - -<dl> - <dt>Blank line</dt> - <dd>You may use blank lines comprised of zero or more space and tab characters.</dd> - <dt>Comment</dt> - <dd>Comments consist of zero or more tabs or spaces followed by a single <code>#</code> character, followed by zero or more characters of comment text. Comments may only be used on their own lines, and cannot be appended to other lines. This means that you cannot specify fragment identifiers.</dd> - <dt>Section header</dt> - <dd>Section headers specify which section of the cache manifest is being manipulated. There are three possible section headers:</dd> -</dl> - -<blockquote> -<table class="standard-table"> - <tbody> - <tr> - <th>Section header</th> - <th>Description</th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td>Switches to the explicit section of the cache manifest (this is the default section).</td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td>Switches to the online whitelist section of the cache manifest.</td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td>Switches to the fallback section of the cache manifest.</td> - </tr> - </tbody> -</table> -</blockquote> - -<dl> - <dd>The section header line may include whitespaces, but must include the colon (<code>:</code>) in the section name.</dd> - <dt>Section data</dt> - <dd>The format for lines of data varies from section to section. In the explicit (<code>CACHE:</code>) section, each line is a valid URI or IRI reference to a resource to cache (no wildcard characters are allowed in this sections). Whitespace is allowed before and after the URI or IRI on each line. In the Fallback section each line is a valid URI or IRI reference to a resource, followed by a fallback resource that is to be served up when a connection with the server cannot be made. In the network section, each line is a valid URI or IRI reference to a resource to fetch from the network (the wildcard character * is allowed in this section). - <div class="note"><strong>Note: </strong>Relative URIs are relative to the cache manifest's URI, not to the URI of the document referencing the manifest.</div> - </dd> -</dl> - -<p>Cache manifest files can switch from section to section at will (each section header can be used more than once), and sections are allowed to be empty.</p> - -<h2 id="Resources_in_an_application_cache">Resources in an application cache</h2> - -<p>An application cache always includes at least one resource, identified by URI. All resources fit into one of the following categories:</p> - -<dl> - <dt>Master entries</dt> - <dd>These are resources added to the cache because a browsing context visited by the user included a document that indicated that it was in this cache using its <code>manifest</code> attribute.</dd> - <dt>Explicit entries</dt> - <dd>These are resources explicitly listed in the application's cache manifest file.</dd> - <dt>Network entries</dt> - <dd>These are resources listed in the application's cache manifest files as network entries.</dd> - <dt>Fallback entries</dt> - <dd>These are resources listed in the application's cache manifest files as fallback entries.</dd> -</dl> - -<div class="note"><strong>Note:</strong> 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.</div> - -<p>Resource categories are described in greater detail below.</p> - -<h3 id="Master_entries">Master entries</h3> - -<p>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 <code><a class="linkification-ext external" href="http://www.foo.bar/entry.html" title="Linkification: http://www.foo.bar/entry.html">http://www.example.com/entry.html</a></code>, which looks like this:</p> - -<pre class="brush: html"><html manifest="example.appcache"> - <h1>Application Cache Example</h1> -</html> -</pre> - -<p>If <code>entry.html</code> is not listed in the <code>example.appcache</code> cache manifest file, visiting the <code>entry.html</code> page causes <code>entry.html</code> to be added to the application cache as a master entry.</p> - -<h3 id="Explicit_entries">Explicit entries</h3> - -<p>Explicit entries are resources that are explicitly listed in the <code>CACHE </code>section of a cache manifest file.</p> - -<h3 id="Network_entries">Network entries</h3> - -<p>The <code>NETWORK</code> 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 <code>NETWORK</code> section are loaded from the server instead of the cache. This lets the browser's security model protect the user from potential security breaches by limiting access to approved resources.</p> - -<p>As an example, you can use network entries to load and execute scripts and other code from the server instead of the cache:</p> - -<pre>CACHE MANIFEST -NETWORK: -/api -</pre> - -<p>The cache manifest section listed above ensures that requests to load resources contained in the <code><a href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> subtree always go to the network without attempting to access the cache.</p> - -<div class="note"><strong>Note</strong>: Simply omitting master entries (files that have the <code>manifest</code> attribute set in the <code>html</code> element) from the manifest file would not have the same result, because master entries will be added—and subsequently served from—the application cache.</div> - -<h3 id="Fallback_entries">Fallback entries</h3> - -<p>Fallback entries are used when an attempt to load a resource fails. For example, let's say the cache manifest file <code><a href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> includes the following content:</p> - -<pre>CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> - -<p>Any request to <code><a href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code> 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 <code>example.html</code> instead.</p> - -<h2 id="Cache_states">Cache states</h2> - -<p>Each application cache has a <strong>state</strong>, 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:</p> - -<dl> - <dt><code>UNCACHED</code></dt> - <dd>A special value that indicates that an application cache object is not fully initialized.</dd> - <dt><code>IDLE</code></dt> - <dd>The application cache is not currently in the process of being updated.</dd> - <dt><code>CHECKING</code></dt> - <dd>The manifest is being fetched and checked for updates.</dd> - <dt><code>DOWNLOADING</code></dt> - <dd>Resources are being downloaded to be added to the cache, due to a changed resource manifest.</dd> - <dt><code>UPDATEREADY</code></dt> - <dd>There is a new version of the application cache available. There is a corresponding <code>updateready</code> event, which is fired instead of the <code>cached</code> event when a new update has been downloaded but not yet activated using the <code>swapCache()</code> method.</dd> - <dt><code>OBSOLETE</code></dt> - <dd>The application cache group is now obsolete.</dd> -</dl> - -<h2 id="Testing_for_updates_to_the_cache_manifest">Testing for updates to the cache manifest</h2> - -<p>You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test <code>window.applicationCache.status</code>.</p> - -<pre class="brush: js">function onUpdateReady() { - alert('found new version!'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> - -<p>To manually start testing for a new manifest file, you can use <code>window.applicationCache.update()</code>.</p> - -<h2 id="Gotchas">Gotchas</h2> - -<ul> - <li>Never access cached files by using traditional GET parameters (like <code>other-cached-page.html?parameterName=value</code>). This will make the browser bypass the cache and attempt to get it from network. To link to cached resources that have parameters parsed in JavaScript use parameters in the hash part of the link, such as <code>other-cached-page.html#whatever?parameterName=value</code>.</li> - <li>When applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. You must update the cache manifest file itself before the browser retrieves and uses the updated files. You can do this programmatically using <code>window.applicationCache.swapCache()</code>, though resources that have already been loaded will not be affected. To make sure that resources are loaded from a new version of the application cache, refreshing the page is ideal.</li> - <li>It's a good idea to set expires headers on your web server for <code>*.appcache</code> files to expire immediately. This avoids the risk of caching manifest files. For example, in Apache you can specify such a configuration as follows:<br> - <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>4.0</td> - <td>3.5</td> - <td>10.0</td> - <td>10.6</td> - <td>4.0</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>2.1</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatNo}}</td> - <td>11.0</td> - <td>3.2</td> - </tr> - </tbody> -</table> -</div> - -<p>Note: Versions of Firefox prior to 3.5 ignore the <code>NETWORK </code>and <code>FALLBACK </code>sections of the cache manifest file.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="http://www.html5rocks.com/en/tutorials/appcache/beginner/" title="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> - <li><a href="http://appcachefacts.info/" title="http://appcachefacts.info/">appcachefacts.info</a> - detailed information on AppCache idiosyncrasies</li> - <li><a href="http://alistapart.com/article/application-cache-is-a-douchebag" title="http://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Application Cache is a Douchebag</a></li> - <li><a href="http://hacks.mozilla.org/2010/01/offline-web-applications/" title="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li> - <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> - <li><a href="http://www.w3.org/TR/offline-webapps/" title="http://www.w3.org/TR/offline-webapps/">W3C Working Group Note: Offline Web Applications</a></li> - <li><a href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage" title="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> - <li><a href="http://manifest-validator.com" title="http://manifest-validator.com">Cache Manifest Validator</a></li> - <li>{{interface("nsIApplicationCache")}}</li> - <li>{{interface("nsIApplicationCacheNamespace")}}</li> - <li>{{interface("nsIApplicationCacheContainer")}}</li> - <li>{{interface("nsIApplicationCacheChannel")}}</li> - <li>{{interface("nsIApplicationCacheService")}}</li> - <li>{{interface("nsIDOMOfflineResourceList")}}</li> - <li><a href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a> (IBM developerWorks)</li> - <li><a href="/en-US/docs/Application_cache_implementation_overview" title="/en-US/docs/Application_cache_implementation_overview">Application cache implementation overview</a></li> -</ul> - -<div>{{HTML5ArticleTOC}}</div> 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 ---- -<h2 id="Introducción">Introducción</h2> - -<p><a href="https://developer.mozilla.org/en-US/docs/HTML/HTML5" title="/en-US/docs/HTML/HTML5">HTML5</a> proporciona un mecanismo de <em>caché de aplicación</em> que permite que las aplicaciones basadas en la web se ejecuten sin conexión. Los desarrolladores pueden usar la interface de <strong>Caché de aplicaciones</strong> (<em>AppCache</em>) para especificar los recursos que el navegador debería guardar en caché y tener disponibles para los usuarios cuando no estén conectados. Las aplicaciones que están en caché se cargan y funcionan correctamente aunque los usuarios hagan clic en el botón recargar cuando no están conectados.</p> - -<p>Usar el caché de aplicaciones le da a la aplicación los siguientes beneficios:</p> - -<ul> - <li>Navegación sin conexión: los usuarios pueden navegar un sitio aún cuando no estén conectados.</li> - <li>Velocidad: los recursos en caché son locales, y por lo tanto, se cargan más rápido.</li> - <li>Carga al servidor reducida: el navegador solamente descarga desde el servidor recursos que han cambiado..</li> -</ul> - -<h3 id="¿Cómo_funciona_el_caché_de_aplicaciones">¿Cómo funciona el caché de aplicaciones?</h3> - -<h3 id="Habilitando_caché_de_aplicaciones">Habilitando caché de aplicaciones</h3> - -<p>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:</p> - -<div> -<pre class="brush: html"><span class="brush: html"><html manifest="ejemplo.appcache"> </span> - ... -</html> -</pre> -</div> - -<p>El atributo manifest referencia un archivo <strong>manifest de caché</strong>, que es un archivo de texto que lista los recursos (archivos) que el navegador deberá guardar en caché para la aplicación.</p> - -<p>Debería incluir el atributo <code>manifest</code> en cada página de la aplicación que quiera guardar en caché. El navegador no guardará páginas que no contengan el atributo <code>manifest</code>, 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 <code>manifest</code> establecido para caché de aplicación.</p> - -<p>Algunos navegadores (ej. Firefox) muestran una notificación la primera vez que un usuario carga una aplicación que usa caché de aplicaciones La barra de notificaciones muestra un mensaje parecido a :</p> - -<p style="margin-left: 40px;">Este sitio web (<code>www.ejemplo.com</code>) está pidiendo guardar datos en su equipo para usar sin conexión. [Permitir] [Nunca para este sitio] [No por ahora]</p> - -<p>El término "offline(-enabled) applications" a veces se refiere específicamente a aplicaciones a las que el usuario ha permitido que usen capacidades sin conexión.</p> - -<h3 id="Cargando_documentos">Cargando documentos</h3> - -<div> -<p>Es uso de caché de aplicaciones modifica el proceso normal de la carga de un documento:</p> - -<ul> - <li>Si existe caché de aplicaciones, el navegador carga el documento y sus recursos asociados directamente desde ahí, sin acceder a la red. Esto acelera el tiempo de carga del documento.</li> - <li>El navegador entonces verifíca si hubo actualizaciones al manifest de caché en el servidor.</li> - <li>Si el manifest de caché fue actualizado, el navegador descarga la nueva versión del archivo y de los recursos listados en él. Esto se realiza en segundo plano y no afecta el rendimiento de forma significativa.</li> -</ul> - -<p>El proceso para cargar documentos y actualizar el caché de aplicaciones está especificado con gran detalle aquí debajo:</p> -</div> - -<ol> - <li>Cuando el navegador visita un documento que incluye el atributo <code>manifest</code>, si no existe caché de 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. </li> - <li>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 <code>checking</code> al objeto <code><a href="https://developer.mozilla.org/en/DOM/window.applicationCache" title="en/DOM/window.applicationCache">window.applicationCache</a></code> y descarga el archivo de manifest, siguiendo las reglas de caché HTTP apropiadas.</li> - <li>Si la copia del manifest actualmente en caché está actualizada, el navegador envía un evento <code>noupdate</code> al objeto <code>applicationCache</code> y el proceso de actualización está completo. Hay que tener en cuenta que si se cambia en el servidor cualquier recurso en caché, se deberá cambiar también el archivo de manifest, para que el navegador sepa que deberá descargar los recursos nuevamente.</li> - <li>Si el archivo de manifest <em>ha</em> cambiado, todos los archivos listados en el manifest—así como los que se agregaron al caché llamando <code><a href="https://developer.mozilla.org/en/nsIDOMOfflineResourceList#add.28.29" title="en/nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a></code>—se descargarán en un caché temporario, siguiendo las reglas de caché HTTP apropiadas. Para cada archivo descargado en este caché temporario, el navegador envía un evento <code>progress</code> al objeto <code>applicationCache</code>. Si ocurre cualquier error, el navegador envía un evento <code>error</code> y la actualización se detiene.</li> - <li>Una vez que todos los archivos han sido recuperados exitosamente, son movidos al caché sin conexión real automáticamente y un evento <code>cached</code> es enviado al objeto <code>applicationCache</code>. Como el documento ya ha sido cargado en el navegador desde caché, la actualización no se mostrará hasta que el documento sea re-cargado (ya sea manualmente o por programa).</li> -</ol> - -<h2 id="Ubicación_del_almacenamiento_y_limpiando_el_caché_sin_conexión">Ubicación del almacenamiento y limpiando el caché sin conexión</h2> - -<p>En Chrome se puede limpiar el caché sin conexión seleccionando "Clear browsing data..." en las preferencias o visitando <a class="external" title="chrome://appcache-internals/">chrome://appcache-internals/</a>. Safari tiene una configuración similar"Vaciar cache" en sus preferencias, pero se requiere el reinicio del navegador.</p> - -<p>En Firefox, el caché sin conexión se guarda en un lugar separado del perfil de Firefox profile—cerca del caché de disco regular:</p> - -<ul> - <li>Windows Vista/7: <code>C:\Users\<usuario>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<nombre de perfil>\OfflineCache</code></li> - <li>Mac/Linux: <code>/Users/<usuario>/Library/Caches/Firefox/Profiles/<salt>.<nombre de perfil>/OfflineCache</code></li> -</ul> - -<p>En Firefox el estado actual del caché de aplicaciones puede ser inspeccionado en la página the <code>about:cache</code> (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.</p> - -<p>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.</p> - -<p>Véase también <a href="https://developer.mozilla.org/en/DOM/Storage#Storage_location_and_clearing_the_data" title="en/DOM/Storage#Storage location and clearing the data">limpiar los datos de almacenamiento de DOM</a>.</p> - -<div> -<p>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 <code>applicationCache</code>. Esto cambia el estado de caché de la aplicación a <code>OBSOLETE</code>.</p> -</div> - -<h2 id="El_archivo_de_manifest_de_caché">El archivo de manifest de caché</h2> - -<h3 id="Referenciando_un_archivo_de_manifest_de_caché">Referenciando un archivo de manifest de caché</h3> - -<p>El atributo <code>manifest</code> 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 <code>text/cache-manifest</code>.</p> - -<div class="note"><strong>Nota: </strong>En servidores Apache, el tipo MIME para los archivos de manifest (.appcache) puede establecerse agregando <code>AddType text/cache-manifest .appcache</code> a un archivo .htaccess dentro del directorio raíz o del mismo directorio que la aplicación.</div> - -<h3 id="Entradas_en_el_archivo_de_manifest_de_caché">Entradas en el archivo de manifest de caché</h3> - -<p>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. </p> - -<h3 id="Ejemplo_1_un_archivo_de_manifest_de_caché_simple">Ejemplo 1: un archivo de manifest de caché simple</h3> - -<div> -<p>El siguiente es un archivo de manifest de caché simple, <code>ejemplo.appcache</code>, para un sitio web imaginario en <span class="nowiki">www.ejemplo.com</span>.</p> - -<pre class="eval">CACHE MANIFEST -# v1 - 2011-08-13 -# Esto es un comentario. -<span class="nowiki">http://www.ejemplo.com/index.html</span> -<span class="nowiki">http://www.ejemplo.com/encabezado.png</span> -<span class="nowiki">http://www.ejemplo.com/blah/blah</span> -</pre> - -<p>Un archivo de manifest de caché puede incluir tres secciones (<code>CACHE</code>, <code>NETWORK</code> y <code>FALLBACK</code>, 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 (<code>CACHE</code>), 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. <code>index.html</code>).</p> - -<p>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 <code>header.png</code> 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.</p> - -<div class="warning"><strong>Importante:</strong> 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.</div> - -<h3 id="Secciones_en_un_archivo_de_manifest_de_caché_CACHE_NETWORK_y_FALLBACK">Secciones en un archivo de manifest de caché: <code>CACHE</code>, <code>NETWORK</code> y <code>FALLBACK</code></h3> - -<p>Un manifest puede tener tres secciones distintas: <code>CACHE</code>, <code>NETWORK</code> y <code>FALLBACK</code>.</p> - -<dl> - <dt><code>CACHE:</code></dt> - <dd>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 <code>CACHE:</code> (o inmediatamente después de la línea <code>CACHE MANIFEST</code>) son guardados en caché explícitamente después de ser descargados la primera vez.</dd> - <dt><code>NETWORK:</code></dt> - <dd>Los archivos listados bajo el encabezado de sección <code>NETWORK:</code> en el archivo de manifest de caché son recursos en <em>lista blanca</em> 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.</dd> - <dt><code>FALLBACK:</code></dt> - <dd>La sección <code>FALLBACK:</code> 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.</dd> -</dl> - -<p>Las secciones <code>CACHE</code>, <code>NETWORK</code> y <code>FALLBACK </code>pueden lsitarse en cualquier orden en el archivo de manifest y cada sección puede aparecer más de una vez en un manifest.</p> - -<h3 id="Ejemplo_2_un_archivo_de_manifest_de_caché_más_completo">Ejemplo 2: un archivo de manifest de caché más completo</h3> - -<p>El siguiente es un archivo de manifest de caché para el sitio web imaginario en <span class="nowiki">www.ejemplo.com</span>:</p> - -<pre class="eval">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 -</pre> - -<p>Este ejemplo usa las secciones <code>NETWORK</code> y <code>FALLBACK</code> para especificar la página <code>network.html</code> que deber ser recuperada desde la red y que la página <code>fallback.html</code> servirá como fallback (ej. en caso que una conexión al servidor no pueda establecerse).</p> - -<h3 id="Estructura_de_un_archivo_de_manifest_de_caché">Estructura de un archivo de manifest de caché</h3> - -<p>Los archivos de manifest de caché deben enviarse con el tipo MIME <code>text/cache-manifest</code>. 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.</p> - -<p>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 (<code>U+000A</code>), retorno de carro (<code>U+000D</code>) o ambos retorno de carro y salto de línea.</p> - -<p>La primera línea del manifest de caché debe consistir en la cadena <code>CACHE MANIFEST</code> (con un solo espacio <code>U+0020</code> entre ambas palabras), seguido de cero o más espacios con caracteres de tabulación. Cualquier otro texto en la línea es ignorado.</p> - -<p>El resto del manifest de caché debe estar compuesto por cero o más de las siguientes líneas:</p> - -<dl> - <dt>Línea en blanco</dt> - <dd>Se pueden usar líneas en blanco compuestas por cero o más espacios y caracteres de tabulación.</dd> - <dt>Comentario</dt> - <dd>Los comentarios consisten en cero o más tabulaciones o espacios seguidos por un caracter <code>#</code> 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.</dd> - <dt>Encabezado de sección</dt> - <dd>Los encabezados de sección especifican qué sección del manifest de caché está siendo manipulada. Hay tres encabezados de sección posibles:</dd> -</dl> - -<blockquote> -<table class="standard-table"> - <tbody> - <tr> - <th>Encabezado de sección</th> - <th>Descripción</th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td>Cambia a la sección explícita del manifest de caché (esta es la sección predeterminada).</td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td>Cambia a la sección de lista blanca del manifest de caché.</td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td>Cambia a la sección fallback del manifest de caché.</td> - </tr> - </tbody> -</table> -</blockquote> - -<dl> - <dd>La línea de encabezado de sección puede incluir espacios en blanco, pero debe incluir los dos puntos (<code>:</code>) en el nombre de sección.</dd> - <dt>Datos de sección</dt> - <dd>El formato de las líneas de datos varía de sección a sección. En la sección explícita (<code>CACHE:</code>), 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). - <div class="note"><strong>Nota: </strong>URIs relativas son relativas a la URI del manifest de caché, no a la URI del documento que hace referencia al manifest.</div> - </dd> -</dl> - -<p>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.</p> - -<h2 id="Recursos_en_un_caché_de_aplicación">Recursos en un caché de aplicación</h2> - -<p>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:</p> - -<dl> - <dt>Entradas maestras</dt> - <dd>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 <code>manifest</code>.</dd> - <dt>Entradas explícitas</dt> - <dd>Estos recursos están listados explícitamente en el archivo de manifest de caché de la aplicación.</dd> - <dt>Entradas de red</dt> - <dd>Estos son recursos listados en el archivo de manifest de caché de la aplicación como entradas de red.</dd> - <dt>Entradas de fallback</dt> - <dd>Estos son recursos listados en el archivo de manifest de caché de la aplicación como entradas de fallback.</dd> -</dl> - -<div class="note"><strong>Nota:</strong> 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.</div> - -<p>Las categorías de recursos se describen con más detalle debajo.</p> - -<h3 id="Entradas_principales">Entradas principales</h3> - -<p>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 <code><a class="linkification-ext external" href="http://www.foo.bar/entry.html" title="Linkification: http://www.foo.bar/entry.html">http://www.ejemplo.com/entrada.html</a></code>, que incluye el siguiente texto:</p> - -<pre class="brush: html"><html manifest="ejemplo.appcache"> - <h1>Ejemplo de cache de aplicacion</h1> -</html> -</pre> - -<p>Si <code>entrada.html</code> no está listado en el archivo de manifest de caché <code>ejemplo.appcache</code>, visitar la pagina <code>entrada.html</code> causa que se agregue al caché de aplicación el archivo <code>entrada.html</code> como entrada maestra.</p> - -<h3 id="Entradas_explícitas">Entradas explícitas</h3> - -<p>Las entradas explícitas son recursos que están listados explicitamente en la seccion <code>CACHE </code>de un archivo de manifest de caché.</p> - -<h3 id="Entradas_de_red">Entradas de red</h3> - -<p>La sección <code>NETWORK</code> 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 <code>NETWORK</code> 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.</p> - -<p>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é:</p> - -<pre>CACHE MANIFEST -NETWORK: -/api -</pre> - -<p>La sección de caché de manifest listada debajo asegura que las peticiones para cargar los recursos contenidos en <code><a class="external" href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> siempre van a la red sin intentar acceder a la caché.</p> - -<div class="note"><strong>Nota</strong>: <span class="short_text" id="result_box" lang="es"><span class="hps">Simplemente</span> <span class="hps">omitiendo</span> <span class="hps">las entradas</span> principales</span> (archivos que tienen el atributo <code>manifest</code> en el elemento <code>html</code>) del archivo manifest no tendrá el mismo resultado, porque las entradas principales serán agregadas—y posteriormente servida por—la aplicación de caché. </div> - -<h3 id="Entradas_fallback">Entradas fallback</h3> - -<p>Las entradas fallback son usadas cuando un intento de cargar los recursos falla. Por ejemplo, digamos que el archivo de anifest de caché <code><a class="external" href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> incluye el siguiente contenido:</p> - -<pre>CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> - -<p>Cualquier petición a <code><a class="external" href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code> o cualquiera de sus directorios <span id="result_box" lang="es"><span class="hps">y</span> <span class="hps">su contenido</span> hace que <span class="hps">el explorador</span> <span class="hps">emita</span> <span class="hps">una solicitud de red</span> <span class="hps">al</span> <span class="hps">intentar cargar el</span> <span class="hps">recurso solicitado</span></span>. 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 <code>example.html</code> en su lugar.</p> - -<h2 id="Estados_de_caché">Estados de caché</h2> - -<p>Cada aplicación de caché tiene un <strong>estado</strong>, 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:</p> - -<dl> - <dt><code>UNCACHED</code></dt> - <dd><span id="result_box" lang="es"><span class="hps">Un valor</span> <span class="hps">especial que indica</span> <span class="hps">que un objeto</span> <span class="hps">caché de la aplicación</span></span> no está inicializado en su totalidad.</dd> - <dt><code>IDLE</code></dt> - <dd>La caché de aplicación no está actualmente en el proceso de actualización.</dd> - <dt><code>CHECKING</code></dt> - <dd>El manifest se ha obtenido y revisado para actualizaciones.</dd> - <dt><code>DOWNLOADING</code></dt> - <dd>Recursos han sido descargados para ser añadidos al caché, debido a un cambio de recursos de manifest.</dd> - <dt><code>UPDATEREADY</code></dt> - <dd>Hay una nueva versión de la aplicación de caché disponible. Hay un correspondiente evento <code>updateready</code>, que es lanzado en lugar del evento <code>cached</code> cuando una nueva actualización acaba de ser descargada pero aún no ah sido activado el método <code>swapCache()</code>.</dd> - <dt><code>OBSOLETE</code></dt> - <dd>La aplicación de caché de grupo es ahora obsoleta.</dd> -</dl> - -<h2 id="Probando_para_actualizaciones_para_el_manifest_de_caché">Probando para actualizaciones para el manifest de caché</h2> - -<p>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 <code>window.applicationCache.status</code>.</p> - -<pre class="brush: js">function onUpdateReady() { - alert('found new version!'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> - -<p> Para comenzar a probar manualmente para un nuevo archivo manifest, puedes usar <code>window.applicationCache.update()</code>.</p> - -<h2 id="Contra_indicaciones">Contra indicaciones</h2> - -<ul> - <li>Nunca accesar aplicacines de caché usando los parámetros tradicionales de GET (como <code>other-cached-page.html?parameterName=value</code>). Esto hará que el navegador omita el caché y trate de obtenerlo mediante la red. <span class="short_text" id="result_box" lang="es"><span class="hps">Para enlazar</span> <span class="hps">a los recursos</span> <span class="hps">almacenados en caché</span></span> que tienen parámetros cambiados a JavaScript usa parámetros en la parte del hash del enlace, como <code>other-cached-page.html#whatever?parameterName=value</code>.</li> - <li>Cuando las aplicaciones son almacenadas en caché, simplemente actualizando los recursos (archivos) que son usados en una página web no son suficientes para actualizar los archivos que han sido almacenados en caché. Debes actualizar el archivo de manifest de caché a sí mismo antes de que el navegador recupere y use los archivos actualizados. Puedes hacer esto programadamente usando <code>window.applicationCache.swapCache()</code>, <span id="result_box" lang="es"><span class="hps">aunque</span> <span class="hps">los recursos</span> <span class="hps">que</span> <span class="hps">ya han sido cargados</span> <span class="hps">no se verán afectados</span></span>. <span id="result_box" lang="es"><span class="hps">Para asegurarse de</span> <span class="hps">que los recursos</span> <span class="hps">se cargan desde</span> <span class="hps">una nueva</span> <span class="hps">versión de la</span> <span class="hps">caché de la aplicación</span><span>,</span> <span class="hps">la actualización de la</span> <span class="hps">página</span> <span class="hps">es ideal</span></span>.</li> - <li>Es una buena idea colocar cabeceras expiradas en tu sitio para los archivos <code>*.appcache</code> para que caduquen inmediatamente. Esto previene el riesgo de almacenar en caché archivos de manifest. Por ejemplo, en Apache puedes especificar <span id="result_box" lang="es"><span class="hps">una</span> <span class="hps">configuración de este tipo</span> <span class="hps">de la siguiente manera</span></span>:<br> - <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> - -<h2 id="Compatibilidad_del_navegador">Compatibilidad del navegador</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Característica</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Soporte básico</td> - <td>4.0</td> - <td>3.5</td> - <td>10.0</td> - <td>10.6</td> - <td>4.0</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Característica</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Soporte básico</td> - <td>2.1</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{ CompatNo() }}</td> - <td>11.0</td> - <td>3.2</td> - </tr> - </tbody> -</table> -</div> - -<p>Nota: Versiones de Firefox anteriores a la 3.5 ignoran las secciones <code>NETWORK y</code> <code>FALLBACK del archivo manifest de caché</code>.</p> - -<h2 id="Ver_también">Ver también</h2> - -<ul> - <li><a class="external" href="http://www.html5rocks.com/en/tutorials/appcache/beginner/" title="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> - <li><a class="external" href="http://appcachefacts.info/" title="http://appcachefacts.info/">appcachefacts.info</a> - información detallada en AppCache idiosyncrasies</li> - <li><a class="external" href="http://hacks.mozilla.org/2010/01/offline-web-applications/" title="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> en hacks.mozilla.org - muestras de una aplicacón offline en demo y explica como funciona.</li> - <li><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> - <li><a class="external" href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage" title="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> - <li>{{ interface("nsIApplicationCache") }}</li> - <li>{{ interface("nsIApplicationCacheNamespace") }}</li> - <li>{{ interface("nsIApplicationCacheContainer") }}</li> - <li>{{ interface("nsIApplicationCacheChannel") }}</li> - <li>{{ interface("nsIApplicationCacheService") }}</li> - <li>{{ interface("nsIDOMOfflineResourceList") }}</li> - <li><a class="external" href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Prepárate para Firefox 3.0 - Una guía para desarrolladores web para las muchas nuevas características en este navegador tan popular, específicamente las características offline</a> (IBM developerWorks)</li> -</ul> - -<p>{{ HTML5ArticleTOC() }}</p> -</div> 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 ---- -<div>{{DefaultAPISidebar("App Cache")}}{{securecontext_header}}{{deprecated_header}}</div> - -<div class="warning"> -<p><strong>Attention !</strong> L'utilisation de la fonction de <em>mise en cache d'application</em> décrite ici est actuellement fortement déconseillée; cette fonctionnalité est <a href="https://html.spec.whatwg.org/multipage/browsers.html#offline">en train d' être retiré de la plate-forme Web</a>. Utiliser <a href="/fr/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service Workers</a> à la place. En fait, à partir de Firefox 44, quand l'<a href="/fr/docs/Web/HTML/Using_the_application_cache">application cache</a> 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 <a href="/fr/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> à la place ({{bug("1204581")}}).</p> -</div> - -<h2 id="Introduction">Introduction</h2> - -<p><a href="/fr/docs/Web/Guide/HTML/HTML5">HTML5</a> supporte la mise en cache hors-ligne de ressources d'applications web; les fichiers sont stockés dans<strong> l'Application Cache </strong><em>(AppCache)</em> - une collection de ressources obtenues depuis un fichier <strong>manifest</strong> (<code>*.appcache</code>) inclue dans une application web.</p> - -<p>L'utilisation d'une application cache permet les bénéfices suivants :</p> - -<ul> - <li>Navigation hors-ligne : les utilisateurs peuvent utiliser un site même s'ils ne sont pas connectés.</li> - <li>Vitesse : les ressources mises en cache sont locales, et se chargent donc plus rapidement.</li> - <li>Réduction de la charge serveur : le navigateur ne télécharge uniquement les ressources qui ont changées sur le serveur.</li> -</ul> - -<div> -<h2 id="Comment_fonctionne_AppCache">Comment fonctionne AppCache</h2> - -<h3 id="Activer_AppCache">Activer AppCache</h3> - -<p>Vous devez, pour utiliser le cache d'application, utiliser l'attribut <code><a href="/fr/docs/Web/HTML/Element/html#attr-manifest">manifest</a> </code>dans l'élément <code><html> </code>comme suit :</p> - -<pre class="brush: html notranslate"><html manifest="example.appcache"> - ... -</html></pre> - -<p>L'attribut <code>manifest</code> spécifie l'URI d'un <strong>manifeste de cache</strong>, qui est un fichier texte qui répertorie les ressources (fichiers) que le navigateur doit mettre en cache pour votre application.</p> - -<p>Vous devez inclure l'attribut <code>manifest</code> 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 <code>manifest</code>, 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 <code>manifest</code> réglé sur le cache de l'application.</p> - -<p>Certains navigateurs dont Firefox vont avertir l'utilisateur la première fois que celui-ci charge votre application par une notification :</p> - -<p>« Ce site internet (<code>www.example.com</code>) veut stocker des données sur votre ordinateur pour une utilisation hors-ligne. [Accepter] [Refuser pour ce site] [Pas maintenant] ».</p> - -<p>Le terme « d'applications (fonctionnant) hors-ligne » est parfois utilisé pour désigner les applications que l'utilisateur a autorisé à travailler hors-ligne.</p> - -<h3 id="Chargement_des_documents">Chargement des documents</h3> - -<p>L'utilisation d'un cache de l'application modifie le processus normal de chargement d'un document :</p> - -<ul> - <li>Si un cache de l'application existe, le navigateur charge le document et ses ressources associées directement à partir de la mémoire cache, sans accéder au réseau. Cela accélère le temps de chargement du document.</li> - <li>Le navigateur vérifie ensuite si le manifeste de cache a été mis à jour sur le serveur.</li> - <li>Si le manifeste de cache a été mis à jour, le navigateur télécharge une nouvelle version du manifeste et les ressources figurant dans ce dernier. Cela se fait en arrière-plan et n'affecte pas les performances de manière significative.</li> -</ul> - -<p>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:</p> - -<ol> - <li>Quand le navigateur visite un document qui contient l'attribut <code>manifest </code>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.</li> - <li>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 <code>checking </code>à l'objet <a href="/fr/docs/Web/API/Window/applicationCache"><code>window.applicationCache</code></a>, puis récupère le manifeste en fonction de la règle de cache HTTP adéquate.</li> - <li>Si la version en cache du manifeste est à jour, l'évènement <code>noupdate </code>est envoyé a l'<code>applicationCache</code>, 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.</li> - <li>Si le manifeste <em>a changé</em>, tous les fichiers dans le manifeste (dont ceux ajoutés au cache lors de l'appel à <a href="/fr/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIDOMOfflineResourceList#add.28.29"><code>applicationCache.add()</code></a>) sont récupérés dans un cache temporaire, en fonction des règles de cache HTTP adéquates. Un évènement <code>progress </code>est envoyé à l'objet <code>applicationCache </code>chaque fois qu'un fichier est récupéré dans le cache temporaire. Un évènement <code>error </code>est envoyé à chaque erreur, et la mise à jour s'arrête.</li> - <li>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 <code>cached </code>est envoyé à l'objet <code>applicationCache</code>. 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).</li> -</ol> - -<h2 id="Emplacement_du_stockage_et_effacement_du_cache_hors-ligne">Emplacement du stockage et effacement du cache hors-ligne</h2> - -<p>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 <code>chrome://appcache-internals/</code>. 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.</p> - -<p>Dans Firefox, les données de cache hors-ligne sont stockées séparément du profil Firefox—à côté du cache disque normal :</p> - -<ul> - <li>Windows Vista/7: <code>C:\Users\<username>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache</code></li> - <li>Mac/Linux: <code>/Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache</code></li> -</ul> - -<p>Dans Firefox l'état actuel du cache hors-ligne est consultable sur la page <code>about:cache</code> (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.</p> - -<p>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é.</p> - -<p>Voir aussi <a href="/fr/docs/DOM/Storage#Storage_location_and_clearing_the_data">effacer les données de stockage DOM</a>.</p> - -<p>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 <code>applicationCache</code>. Le statut du cache de l'application est alors <code>OBSOLETE</code>.</p> - -<h2 id="Le_manifeste_du_cache">Le manifeste du cache</h2> - -<h3 id="Référencement_dun_fichier_de_manifeste_de_cache">Référencement d'un fichier de manifeste de cache</h3> - -<p>L'attribut <code>manifest</code> 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 <code>text/cache-manifest</code>.</p> - -<div class="note"><strong>Note: </strong>Sur les serveurs Apache, le MIME type pour les fichiers manifest (.appcache) peut être défini par l'ajout de <code>AddType text/cache-manifest .appcache</code> à un fichier a .htaccess soit à l'intérieur du répertoire racine, soit le même répertoire que l'application.</div> - -<h3 id="Les_entrées_dans_un_manifeste_de_cache">Les entrées dans un manifeste de cache</h3> - -<p>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.</p> - -<h3 id="Example_1_Un_fichier_manifeste_simple">Example 1: Un fichier manifeste simple</h3> - -<p>Ci-dessous, un exemple simple de manifeste — <code>example.appcache</code> utilisé par le site imaginaire www.example.com:</p> - -<pre class="notranslate">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 -</pre> - -<p>Il n'y a pas, dans cet exemple, d'en-tête de section, donc toutes les lignes sont supposées être des sections (<code>CACHE:</code>) explicites. On peut aussi utiliser des URL relatives (<code>index.html</code>, …)</p> - -<p>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 <code>header.png</code>), vous devez changer le manifeste pour signaller au navigateur qu'il doit rafraîchir le cache, et, comme <code>header.png</code> 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.</p> - -<div class="warning"><strong>Important:</strong> 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.</div> - -<h3 id="Des_sections_dans_un_manifeste_de_cache_CACHE_NETWORK_et_FALLBACK">Des sections dans un manifeste de cache: <code>CACHE</code>, <code>NETWORK</code>, et <code>FALLBACK</code></h3> - -<p>Un manifeste peut avoir trois sections distinctes: <code>CACHE</code>, <code>NETWORK</code>, et <code>FALLBACK</code>.</p> - -<dl> - <dt><code>CACHE:</code></dt> - <dd>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.</dd> - <dt><code>NETWORK:</code></dt> - <dd>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 *.</dd> - <dt><code>FALLBACK:</code></dt> - <dd>Le <code>FALLBACK:</code> 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.</dd> -</dl> - -<p>Les sections <code>CACHE</code>, <code>NETWORK</code>, 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.</p> - -<h3 id="Example_2_Un_manifeste_de_cache_plus_complet">Example 2 : Un manifeste de cache plus complet</h3> - -<p>Voici un exemple plus complet de manifeste pour notre site imaginaire www.example.com.</p> - -<pre class="notranslate">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</pre> - -<p>Nous utilisons dans cet exemple les sections <code>FALLBACK </code>et <code>NETWORK</code> pour préciser que la page <code>network.html</code> doit toujours être récupérée depuis le réseau et que la page <code>fallback.html</code> doit être utilisée comme ressource de secours, par exemple si la connexion au serveur ne peut être établie.</p> - -<h3 id="Structure_dun_manifeste">Structure d'un manifeste</h3> - -<p>Les manifestes doivent être servis avec le type MIME <code>text/cache-manifest</code>, et toutes les ressources servies en utilisant ce type MIME doivent respecter la syntaxe d'un manifeste, comme défini ici.</p> - -<p>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 (<code>U+000A</code>), retour chariot (<code>U+000D</code>), ou les deux.</p> - -<p>La première ligne du manifeste doit être la chaine <code>CACHE MANIFEST</code> (séparé par un simple espace <code>U+0020</code>), suivi par aucun ou plusieurs espaces ou tabulations. Tout autre texte sur la ligne sera ignoré.</p> - -<p>Le reste du manifeste peut contenir 0 ou plusieurs lignes :</p> - -<dl> - <dt>Lines vides</dt> - <dd>Vous pouvez utiliser les lignes vides comprenant 0 ou plusieurs espaces ou tabulations.</dd> - <dt>Commentaire</dt> - <dd>Les commentaires consistent en 0 ou plusieurs espaces ou tabulations suivis du caractère <code>#</code>, 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.</dd> - <dt>Section de tête</dt> - <dd>La <code>section header</code> précise la section du cache qui est manipulée. Il en existe trois types:</dd> -</dl> - -<blockquote> -<table class="standard-table" style="height: 130px; width: 535px;"> - <tbody> - <tr> - <th>Section header</th> - <th>Description</th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td>Passe à la section explicite. C'est la section par défaut.</td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td>Passe à la section des sections en ligne sur la liste blanche.</td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td>Passe à la section de secours.</td> - </tr> - </tbody> -</table> -</blockquote> - -<dl> - <dd>La ligne d'en-tête de section peut contenir des espaces, mais doit inclure un « : » dans le nom de la section.</dd> - <dt>Section data</dt> - <dd>Le format des lignes de données varie selon les sections. Dans la section explicite (<code>CACHE:</code>) 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). - <div class="note"><strong>Note: </strong>Les URI relatives pointent vers les URI du manifeste, et non vers les URI du document qui référence le manifeste.</div> - </dd> -</dl> - -<p>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.</p> - -<h2 id="Les_ressources_dans_AppCache">Les ressources dans AppCache</h2> - -<p>Le cache inclue toujours au moins une ressource, identifiée par URI. Toutes les ressources répondent à une des catégories suivantes :</p> - -<dl> - <dt>Entrées Maitres</dt> - <dd>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 <code>manifest</code>.</dd> - <dt>Entrées Explicites</dt> - <dd>Il s'agit de ressources listées dans le manifeste du cache.</dd> - <dt>Entrées Network</dt> - <dd>Il s'agit de ressources listées dans le manifeste du cache comme entrées de network.</dd> - <dt>Entrées Fallback</dt> - <dd>Il s'agit de ressources listées dans le manifeste du cache comme entrées de fallback.</dd> -</dl> - -<div class="note"><strong>Note : </strong>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.</div> - -<p>Les catégories ressources sont décrites en détail ci-dessous.</p> - -<h3 id="Entrées_Maitres">Entrées Maitres</h3> - -<p>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 <code><a class="linkification-ext external" href="https://www.foo.bar/entry.html">https://www.example.com/entry.html</a></code>, qui ressemble à ça :</p> - -<pre class="brush: html notranslate"><html manifest="example.appcache"> - <h1>Application Cache Example</h1> -</html> -</pre> - -<p>Si <code>entry.html</code> n'est pas inclue dans le manifeste, visiter la page <code>entry.html</code> provoquera l'ajout de la page <code>entry.html</code> dans le cache de l'application comme une master entry.</p> - -<h3 id="Entrées_Explicites">Entrées Explicites</h3> - -<p>Les entrées explicites sont des ressources explicitement listées dans la section <code>CACHE </code>d'un manifeste de cache.</p> - -<h3 id="Entrées_Network">Entrées Network</h3> - -<p>Les entrées listées dans <code>NETWORK :</code> peuvent contenir plusieurs ou aucune ressource que l'application requiert lors d'un accès en ligne. C'est principalement une <em>liste blanche en ligne</em>. Les URIS spécifiées dans la section <code>NETWORK</code> 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.</p> - -<div class="note"><strong>Note :</strong> La <em>liste blanche en ligne</em> est ignorée pour les versions de Firefox antérieures à 3.5.</div> - -<p>Vous pouvez l'utiliser pour, par exemple, charger et exécuter des scripts et d'autres codes depuis le serveur au lieu du cache. :</p> - -<pre class="notranslate">CACHE MANIFEST -NETWORK: -/api -</pre> - -<p>Ceci assure que les requêtes téléchargent les ressources contenues dans <code><a class="external" href="https://www.example.com/api/" rel="freelink">https://www.example.com/api/</a></code> viendront toujours du réseau sans essayer d'accéder au cache.</p> - -<div class="note"><strong>Note </strong>: Juste omettre les <em>master entries</em> (les fichiers qui ont l'attribut <code>manifest</code> défini dans l'élément <code>html</code>) dans le manifeste n'aurait pas le même comportement parce que les <em>master entries</em> seront ajoutées — et donc servies depuis— le cache. </div> - -<h3 id="Entrées_Fallback">Entrées Fallback</h3> - -<p>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é à <code><a class="external" href="https://www.example.com/example.appcache" rel="freelink">https://www.example.com/example.appcache</a></code>, et qui contient :</p> - -<pre class="notranslate">CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> - -<p>Toute requête vers <code><a class="external" href="https://www.example.com/example/bar/" rel="freelink">https://www.example.com/example/bar/</a></code> 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 <code>example.html</code> sera chargé à la place.</p> - -<h2 id="Les_états">Les états</h2> - -<p>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 :</p> - -<dl> - <dt><code>UNCACHED</code></dt> - <dd>Une valeur spéciale qui indique qu'un object <em>application cache</em> n'est pas complètement initialisée.</dd> - <dt><code>IDLE</code></dt> - <dd>Le cache n'est pas en cours de mise à jour.</dd> - <dt><code>CHECKING</code></dt> - <dd>Le manifeste est en train d'être contrôlé pour d'éventuelles mises à jour.</dd> - <dt><code>DOWNLOADING</code></dt> - <dd>Des ressources sont en train d'être téléchargées pour être ajoutées au cache, dû à un changement du manifeste.</dd> - <dt><code>UPDATEREADY</code></dt> - <dd>Il y a une nouvelle version du cache disponible. Il y a un évènement <code>updateready</code> correspondant, qui est lancé au lieu de l'évènement <code>cached</code> quand une nouvelle mise à jour a été téléchargée mais pas encore activée via la méthode <code>swapCache()</code>.</dd> - <dt><code>OBSOLETE</code></dt> - <dd>Le groupe de caches est maintenant obsolète.</dd> -</dl> - -<h2 id="Test_pour_les_mises_à_jour_des_manifestes_de_cache">Test pour les mises à jour des manifestes de cache</h2> - -<p>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 <code>window.applicationCache.status</code>.</p> - -<pre class="brush: js notranslate">function onUpdateReady() { - console.log('nouvelle version trouvée !'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> - -<p>Pour démarrer manuellement le test pour un nouveau manifeste de cache, vous pouvez utilisez <code>window.applicationCache.update()</code>.</p> - -<h2 id="Pièges">Pièges</h2> - -<ul> - <li>Ne jamais accéder à des fichiers mis en cache à l'aide des paramètres GET traditionnels (comme <code>other-cached-page.html?parameterName=value</code>). Cela rendra le contournement du navigateur du cache et de tenter de l'obtenir à partir du réseau. Pour créer un lien vers les ressources mises en cache qui ont des paramètres analysés dans les paramètres d'utilisation de JavaScript dans la partie de hach de la liaison, comme <code>other-cached-page.html#whatever?parameterName=value</code>.</li> - <li>Lorsque les applications sont mises en cache, mettant simplement à jour les ressources (fichiers) qui sont utilisés dans une page Web mais cela ne suffit pas à mettre à jour les fichiers qui ont été mis en cache. Vous devez mettre à jour le fichier manifeste de cache lui-même avant que le navigateur récupère et utilise les fichiers mis à jour. Vous pouvez le faire par programme<code>window.applicationCache.swapCache()</code>, si les ressources qui ont déjà été chargées ne seront pas affectés. Pour vous assurer que les ressources sont chargées à partir d'une nouvelle version du cache de l'application, rafraîchir la page est idéal.</li> - <li>Il est une bonne idée de mettre des en-têtes expirés sur votre serveur web pour les fichiers * .appcache pour qu'ils expirent immédiatement. Cela évite le risque de mise en cache des fichiers manifestes. Par exemple, dans Apache, vous pouvez spécifier une telle configuration comme suit:<br> - <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> - -<h2 id="Compatibilité_des_navigateurs">Compatibilité des navigateurs</h2> - -<div class="hidden">Le tableau de compatibilité de cette page a été généré à partir de données structurées. Si vous souhaitez contribuer à ces données, n'hésitez pas à consulter <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> et à nous envoyer une <em>pull request</em>.</div> - -<p>{{Compat("html.elements.html.manifest")}}</p> - -<h2 id="Voir_aussi">Voir aussi</h2> - -<ul> - <li><a href="https://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> - <li><a href="https://appcache.offline.technology/">Appcache Facts</a> - detailed information on AppCache idiosyncrasies</li> - <li><a href="https://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Application Cache is a Douchebag</a> - <ul> - <li><a href="https://flailingmonkey.com/application-cache-not-a-douchebag">The Application Cache is no longer a Douchebag</a> - an overview of the app cache debugging tools added in Firefox 23.</li> - </ul> - </li> - <li><a href="https://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li> - <li><a href="https://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> - <li><a href="https://www.w3.org/TR/offline-webapps/">W3C Working Group Note: Offline Web Applications</a></li> - <li><a href="https://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> - <li><a href="https://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a> (IBM developerWorks)</li> - <li><a href="/fr/docs/Application_cache_implementation_overview">Application cache implementation overview</a></li> - <li><a href="https://www.onlinewebcheck.com/check.php?adv=1">OnlineWebCheck.com - Check manifeste file syntax (application Windows)</a></li> -</ul> -</div> 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 ---- -<h2 id="Introduzione">Introduzione</h2> - -<p><a href="/en-US/docs/HTML/HTML5" title="HTML/HTML5">HTML5</a> possiede un meccanismo di <em>application caching</em> che permette alle applicazioni web-based di funzionare anche offline. Gli sviluppatori possono utilizzare l'interfaccia <strong>Application Cache</strong> (<em>AppCache</em>) 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.</p> - -<p>L'uso dell'application cache fornisce all'applicazione i seguenti benefici:</p> - -<ul> - <li>Navigazione offline: gli utenti possono navigare un sito anche se sono offline.</li> - <li>Velocità: le risorse sono memorizzate in locale, quindi si caricano più velocemente.</li> - <li>Riduzione del carico server: il browser scarica dal server solo le risorse che sono state modificate.</li> -</ul> - -<h2 id="Come_funziona_l'application_cache">Come funziona l'application cache</h2> - -<h3 id="Abilitare_l'application_cache">Abilitare l'application cache</h3> - -<p>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:</p> - -<div style="overflow: hidden;"> -<pre class="brush: html"><html manifest="example.appcache"> - ... -</html> -</pre> -</div> - -<p>L'attributo <code>manifest<strong> </strong></code>fa riferimento ad un <strong>cache manifest</strong>, un file di testo che elenca tutte le risorse (files) che il browser deve memorizzare per la tua applicazione.</p> - -<p>Bisogna includere l'attributo <code>manifest</code> in tutte le pagine dell'applicazione che vuoi memorizzare nella cache, il browser non memorizza le pagine che non contengono l'attributo <code>manifest</code>, 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 <code>manifest</code> settato sull'application cache.</p> - -<p>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:</p> - -<p style="margin-left: 40px;">Questo sito web (<code>www.example.com</code>) richiede di salvare dati sul computer per l'utilizzo non in linea. [Permetti] [Mai per questo sito] [Non adesso]</p> - -<p>Il termine "offline(-enabled) applications" qualche volta fa riferimento alle applicazioni che l'utente ha esplicitamente abilitato ad utilizzare le capacità offline.</p> - -<h3 id="Caricare_documenti">Caricare documenti</h3> - -<p>L'uso dell'application cache modifica il normale processo di caricamento del documento:</p> - -<ul> - <li>Se esiste un'application cache, il browser carica il documento e le sue risorse associate direttamente dalla cache, senza accedere alla rete. Ciò velocizza il tempo di caricamento del documento.</li> - <li>Il browser quindi controlla se il cache manifest è stato aggiornato sul server.</li> - <li>Se il cache manifest è stato aggiornato, il browser scarica la nuova versione e le risorse elencate. Quest'operazione viene eseguita in background e non influenza la performance significativamente.</li> -</ul> - -<p>Il processo di caricamento del documento ed aggiornamento dell'application cache è specificato in maggior dettaglio qui sotto:</p> - -<ol> - <li>Quando il browser visita un documento che include l'attributo <code>manifest</code>, 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.</li> - <li>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 <code>checking</code> all'oggetto <code><a href="/en-US/docs/DOM/window.applicationCache" title="DOM/window.applicationCache">window.applicationCache</a></code> e processa il file manifest, seguendo le appropriate regole di chaching HTTP.</li> - <li>Se la copia attualmente memorizzata del manifest è aggiornata, il browser invia un evento<code> noupdate</code> all'oggetto <code>applicationCache</code>, 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.</li> - <li>Se il file manifest è stato modificato, tutti i file elencati in esso - così come quelli aggiunti alla cache utilizzando <code><a href="/en-US/docs/nsIDOMOfflineResourceList#add.28.29" title="nsIDOMOfflineResourceList#add.28.29">applicationCache.add() </a></code>- 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 <code>progress</code> all'oggetto <code>applicationCache</code>. In caso di errore, il browser invia un evento <code>error</code> e blocca l'aggiornamento dell'application cache.</li> - <li>Una volta che tutti i files sono stati recuperati con successo, vengono automaticamente spostati nella vera cache offline, e viene inviato un evento <code>cached</code> all'oggetto<code> applicationCache</code>. 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).</li> -</ol> - -<h2 id="Percorso_di_memorizzazione_e_cancellazione_della_cache_offline">Percorso di memorizzazione e cancellazione della cache offline</h2> - -<p>Su Chrome è possibile cancellare la cache offline sia selezionando "Clear browsing data..." dalle preferenze, oppure visitando <a title="chrome://appcache-internals/">chrome://appcache-internals/</a>. Safari ha una voce "Svuota cache" simile nelle sue preferenze, ma potrebbe essere necessario riavviare il browser.</p> - -<p>Su Firefox, i dati della cache offline vengono memorizzati separatamente dal profilo Firefox — insieme ai dati degli altri programmi installati:</p> - -<ul> - <li>Windows Vista/7: <code>C:\Users\<username>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache</code></li> - <li>Mac/Linux: <code>/Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache</code></li> -</ul> - -<p>Su Firefox è possibile ispezionare lo stato della cache offline sulla pagina <code>about:cache</code> (box "Offline cache device"). La cache offline può essere cancellata separatamente per ogni sito utilizzando il tasto "Rimuovi..." presente in:<br> - Firefox -> Opzioni -> Avanzate -> Rete -> Dati non in linea e informazioni utente.</p> - -<p>Nelle versioni precedenti a Firefox 11, l'application cache non poteva essere cancellata utilizzando<br> - Tools -> Clear Recent History<br> - oppure<br> - Tools -> Options -> Advanced -> Network -> Offline data -> Clear Now Questo bug è stato fixato nelle versioni successive.</p> - -<p>Vedi anche <a href="/en-US/docs/DOM/Storage#Storage_location_and_clearing_the_data" title="DOM/Storage#Storage location and clearing the data">clearing the DOM Storage data</a>.</p> - -<p>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 <code>applicationCache</code>. Questo imposta lo stato dell'application cache su<code> OBSOLETE</code>.</p> - -<h2 id="Il_file_cache_manifest">Il file cache manifest</h2> - -<h3 id="Includere_un_file_cache_manifest">Includere un file cache manifest</h3> - -<p>L'attributo <code>manifest</code> 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 <code>text/cache-manifest</code>.</p> - -<div class="note"><strong>Nota: </strong>Sui server Apache, il MIME type per i file manifest (.appcache) può essere impostato aggiungendo <code>AddType text/cache-manifest .appcache</code> ad un file .htaccess posizionato nella cartella root, oppure nella stessa cartella dell'applicazione.</div> - -<h3 id="Le_voci_in_un_file_cache_manifest">Le voci in un file cache manifest</h3> - -<p>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.</p> - -<h3 id="Esempio_1_un_semplice_cache_manifest">Esempio 1: un semplice cache manifest</h3> - -<p>Il seguente è un semplice file di cache manifest, <code>example.appcache</code>, per un ipotetico sito web all'indirizzo <span class="nowiki">www.example.com</span>.</p> - -<pre>CACHE MANIFEST -# v1 - 2011-08-13 -# This is a comment. -<span class="nowiki">http://www.example.com/index.html</span> -<span class="nowiki">http://www.example.com/header.png</span> -<span class="nowiki">http://www.example.com/blah/blah</span> -</pre> - -<p>Un file cache manifest può includere 3 sezioni (<code>CACHE</code>, <code>NETWORK</code>, e <code>FALLBACK</code>, 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 (<code>CACHE</code>), 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. <code>index.html</code>).</p> - -<p>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 <code>header.png</code> 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.</p> - -<div class="warning"><strong>Importante:</strong> 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.</div> - -<h3 id="Le_sezioni_di_un_file_cache_manifest_CACHE_NETWORK_e_FALLBACK">Le sezioni di un file cache manifest: <code>CACHE</code>, <code>NETWORK</code>, <code>e FALLBACK</code></h3> - -<p>Un manifest può avere 3 sezioni distine: <code>CACHE</code>, <code>NETWORK</code>, <code>e FALLBACK</code>.</p> - -<dl> - <dt><code>CACHE:</code></dt> - <dd>Questa è la sezione di default per le voci in un cache manifest. I files elencati sotto l'header della sezione <code>CACHE:</code> (oppure subito dopo la riga <code>CACHE MANIFEST</code>) sono esplicitamente memorizzati nella cache dopo che vengono scaricati per la prima volta.</dd> - <dt><code>NETWORK:</code></dt> - <dd>I files elencati sotto l'header della sezione <code>NETWORK:</code> 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.</dd> - <dt><code>FALLBACK:</code></dt> - <dd>Nella sezione <code>FALLBACK:</code> 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.</dd> -</dl> - -<p>Le sezioni <code>CACHE</code>, <code>NETWORK</code>, e <code>FALLBACK </code>possono essere elencate in qualsiasi ordine, ogni sezione può apparire più volte nello stesso cache manifest.</p> - -<h3 id="Example_2_un_cache_manifest_più_completo">Example 2: un cache manifest più completo</h3> - -<p>Il seguente è un esempio più completo di un cache manifest per un ipotetico sito web all'indirizzo <span class="nowiki">www.example.com</span>.</p> - -<pre>CACHE MANIFEST -# v1 2011-08-14 -# This is another comment -index.html -cache.html -style.css -image1.png - -# Use from network if available -NETWORK: -network.html - -# Fallback content -FALLBACK: -/ fallback.html -</pre> - -<p>Questo esempio utilizza le sezioni <code>NETWORK</code> e <code>FALLBACK</code> per specificare che la pagina <code>network.html</code> deve essere sempre prelevata dalla rete e che la pagina <code>fallback.html</code> deve essere servita nel caso una risorsa non sia disponibile (es. nel caso sia impossibile stabilire una connessione col server).</p> - -<h3 id="Struttura_di_un_file_cache_manifest">Struttura di un file cache manifest</h3> - -<p>Un cache manifest deve essere servito con il MIME type <code>text/cache-manifest</code>. Tutte le risorse servite utilizzando questo MIME type devono seguire la sintassi per l'application cache manifest, come definito in questa sezione.</p> - -<p>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 (<code>U+000A</code>), dal carriage return (<code>U+000D</code>), o da entrambi i caratteri.</p> - -<p>La prima riga del cache manifest deve obbligatoriamente essere la stringa <code>CACHE MANIFEST</code> (con un singolo spazio <code>U+0020</code> tra le due parole), seguita da zero o pià caratteri di tabulazione. Qualsiasi altro testo su questa riga verrà ignorato.</p> - -<p>Il resto del manifesto cache deve essere composto da zero o più delle seguenti righe:</p> - -<dl> - <dt>Righe vuote</dt> - <dd>È possibile utilizzare righe vuote composte da zero o più spazi e/o caratteri di tabulazione (tab).</dd> - <dt>Commenti</dt> - <dd>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.</dd> - <dt>Header della sezione</dt> - <dd>Gli header di sezione specificano quale sezione del cache manifest stiamo per manipolare. Ci sono 3 possibili tipi di header:</dd> -</dl> - -<blockquote> -<table class="standard-table"> - <tbody> - <tr> - <th>Header di sezione</th> - <th>Descrizione</th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td>Sezione che definisce quali risorse memorizzare nella cache (questa è la sezione di default, se l'header non è specificato).</td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td>Sezione che definisce quali risorse devono essere sempre scaricate dalla rete.</td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td>Sezione che definisce dei fallback nel caso una risorsa risulti non disponibile.</td> - </tr> - </tbody> -</table> -</blockquote> - -<dl> - <dd>L'header di sezione può includere spazi, ma deve includere i due punti (:) nel nome della sezione.</dd> - <dt>dati della sezione</dt> - <dd>Il formato per le righe di dati varia da sezione a sezione. In quella esplicita (<code>CACHE:</code>), 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 *). - <div class="note"><strong>Note: </strong>Gli URI relativi sono relativi all'URI del cache manifest, non all'URI del documento che fa riferimento al cache manifest.</div> - </dd> -</dl> - -<p>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.</p> - -<h2 id="Risorse_nell'application_cache">Risorse nell'application cache</h2> - -<p>Un application cache include sempre almeno una risorsa, identificata da un URI. Tutte le risorse rientrano in una delle seguenti categorie:</p> - -<dl> - <dt>Master entries</dt> - <dd>Queste risorse sono aggiunte alla cache perchè sono legate ad una pagina che includeva l'attributo <code>manifest</code>.</dd> - <dt>Explicit entries</dt> - <dd>Le risorse esplicitamente indicate nel cache manifest.</dd> - <dt>Network entries</dt> - <dd>Le risorse elencate nel file manifest dell'application cache che devono essere sempre recuperate dalla rete.</dd> - <dt>Fallback entries</dt> - <dd>Le risorse elencate nel file manifest che devono essere utilizzate come alternativa ad una risorsa non raggiungibile.</dd> -</dl> - -<div class="note"><strong>Note:</strong> Una risorsa può rientrare in più categorie, per esempio può apparire sia nella sezione esplicita che in quella di fallback.</div> - -<p>Le categorie di risorse sono descritte in dettaglio qui di seguito.</p> - -<h3 id="Master_entries">Master entries</h3> - -<p>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 <code><a class="linkification-ext external" href="http://www.foo.bar/entry.html" title="Linkification: http://www.foo.bar/entry.html">http://www.example.com/entry.html</a></code>, composto in questa maniera:</p> - -<pre class="brush: html"><html manifest="example.appcache"> - <h1>Application Cache Example</h1> -</html> -</pre> - -<p>se <code>entry.html</code> non è elencato nel file cache manifest <code>example.appcache</code>, basta visitare la pagina per farla aggiungere all'application cache in qualità di master entry.</p> - -<h3 id="Explicit_entries">Explicit entries</h3> - -<p>Le Explicit entries sono le risorse esplicitamente elencate in una sezione <code>CACHE </code>del file cache manifest.</p> - -<h3 id="Network_entries">Network entries</h3> - -<p>La sezione <code>NETWORK</code> 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 <code>NETWORK</code> 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.</p> - -<p>Per esempio, si può utilizzare la lista delle risorse network per caricare ed eseguire script ed altro codice dal server invece che dalla cache:</p> - -<pre>CACHE MANIFEST -NETWORK: -/api -</pre> - -<p>La sezione del cache manifest mostrata qui sopra assicura che tutte le richieste di files contenuti nella sottocartella <code><a href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> vengano sempre caricate dalla rete senza accedere alla cache.</p> - -<div class="note"><strong>Note</strong>: Omettere semplicemente le master entries (i files che contengono l'attributo <code>manifest</code> nell'elemento <code>html</code>) 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.</div> - -<h3 id="Fallback_entries">Fallback entries</h3> - -<p>Fallback entries sono utilizzate quando fallisce il tentativo di caricare una risorsa. Per esempio, diciamo che il cache manifest <code><a href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> includa il seguente contenuto:</p> - -<pre>CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> - -<p>Qualsiasi richiesta a<code><a href="http://www.example.com/example/bar/" rel="freelink"> http://www.example.com/example/bar/</a></code> 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 <code>example.html</code> al suo posto.</p> - -<h2 id="Stati_della_cache">Stati della cache</h2> - -<p>Ogni application cache possiede uno <strong>stato</strong>, 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:</p> - -<dl> - <dt><code>UNCACHED</code></dt> - <dd>Un valore speciale che indica che l'oggetto application cache non è inizializzato completamente.</dd> - <dt><code>IDLE</code></dt> - <dd>L'application cache non è attualmente in fase di aggiornamento.</dd> - <dt><code>CHECKING</code></dt> - <dd>Il manifest è in fase di prelievo e controllo aggiornamenti.</dd> - <dt><code>DOWNLOADING</code></dt> - <dd>Le risorse sono in fase di scaricamento per essere aggiunte alla cache, a causa di una risorsa modificata nel manifest.</dd> - <dt><code>UPDATEREADY</code></dt> - <dd>C'è una nuova versione dell'application cache disponibile. C'è un evento corrispondente <code>updateready</code>, che è lanciato al posto dell'evento <code>cached</code> quando un nuovo aggiornamento è stato scaricato ma non ancora attivato tramite il metodo <code>swapCache()</code>.</dd> - <dt><code>OBSOLETE</code></dt> - <dd>Il gruppo application cache è obsoleto.</dd> -</dl> - -<h2 id="Controllare_gli_aggiornamenti_per_il_cache_manifest">Controllare gli aggiornamenti per il cache manifest</h2> - -<p>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 <code>window.applicationCache.status</code>.</p> - -<pre class="brush: js">function onUpdateReady() { - alert('found new version!'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> - -<p>Per testare manualmente un nuovo file manifest, è possibile utilizzare <code>window.applicationCache.update()</code>.</p> - -<h2 id="Trappole_da_evitare_(aka_Gotchas)">Trappole da evitare (aka Gotchas)</h2> - -<ul> - <li>Non accedere mai ai file nella cache utilizzando i parametri tradizionali della GET (es. <code>other-cached-page.html?parameterName=value</code>). In questo modo il browser ignorerà la cache e andrà a prendere il file dalla rete. Per linkare risorse nella cache che hanno parametri parsati in Javascript, utilizzare i parametri dopo l'hash (#), come per esempio: <code>other-cached-page.html#whatever?parameterName=value</code>.</li> - <li>Quando le applicazioni sono memorizzate nella cache, non è sufficiente aggiornare i files nella cache che sono utilizzati nella pagina web per aggiornarli. E' necessario aggiornare anche il file cache manifest stesso prima che il browser prelevi ed utilizzi i files aggiornati. Si può fare tramite programmazione utilizzando <code>window.applicationCache.swapCache()</code>, <span id="result_box" lang="it"><span class="hps">anche se</span> <span class="hps">le risorse</span> <span class="hps">che sono state già</span> <span class="hps">caricate</span> <span class="hps">non saranno interessate</span></span>. <span id="result_box" lang="it"><span class="hps">Per assicurarsi</span> <span class="hps">che le risorse</span> <span class="hps">vengono caricate da</span> <span class="hps">una</span> <span class="hps">nuova versione della</span> <span class="hps">cache dell'applicazione</span><span>,</span> <span class="hps">ricaricare la pagina</span> <span class="hps">è l'ideale</span></span>.</li> - <li>Una buona prassi è quella di settare gli expires headers sul tuo web server per far sì che i files <code>*.appcache</code> scadano immediatamente. Questo evita il rischio di inserire nella cache il cache manifest stesso. Per esempio, su Apache è possibile impostare questo comportamento nella seguente:<br> - <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> - -<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>4.0</td> - <td>3.5</td> - <td>10.0</td> - <td>10.6</td> - <td>4.0</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>2.1</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatNo}}</td> - <td>11.0</td> - <td>3.2</td> - </tr> - </tbody> -</table> -</div> - -<p>Nota: Le versioni di Firefox precedenti alla 3.5 ignorano le sezioni <code>NETWORK </code>e <code>FALLBACK </code>del file cache manifest.</p> - -<h2 id="Vedi_anche">Vedi anche</h2> - -<ul> - <li><a href="http://www.html5rocks.com/en/tutorials/appcache/beginner/" title="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> - <li><a href="http://appcachefacts.info/" title="http://appcachefacts.info/">appcachefacts.info</a> - informazioni dettagliate delle idiosincrasie sull'AppCache</li> - <li><a href="http://alistapart.com/article/application-cache-is-a-douchebag" title="http://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Application Cache is a Douchebag</a> - <ul> - <li><a href="http://flailingmonkey.com/application-cache-not-a-douchebag" title="http://flailingmonkey.com/application-cache-not-a-douchebag">The Application Cache is no longer a Douchebag</a> - una panoramica sui tool di debug per l'app cache presenti in Firefox 23.</li> - </ul> - </li> - <li><a href="http://hacks.mozilla.org/2010/01/offline-web-applications/" title="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> su hacks.mozilla.org - demo di un app offline e speigazione di come funziona.</li> - <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> - <li><a href="http://www.w3.org/TR/offline-webapps/" title="http://www.w3.org/TR/offline-webapps/">W3C Working Group Note: Offline Web Applications</a></li> - <li><a href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage" title="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> - <li><a href="http://manifest-validator.com" title="http://manifest-validator.com">Cache Manifest Validator</a></li> - <li>{{interface("nsIApplicationCache")}}</li> - <li>{{interface("nsIApplicationCacheNamespace")}}</li> - <li>{{interface("nsIApplicationCacheContainer")}}</li> - <li>{{interface("nsIApplicationCacheChannel")}}</li> - <li>{{interface("nsIApplicationCacheService")}}</li> - <li>{{interface("nsIDOMOfflineResourceList")}}</li> - <li><a href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a> (IBM developerWorks)</li> - <li><a href="/en-US/docs/Application_cache_implementation_overview" title="/en-US/docs/Application_cache_implementation_overview">Application cache implementation overview</a></li> -</ul> - -<div>{{HTML5ArticleTOC}}</div> 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 ---- -<div class="blockIndicator warning"> -<p><strong>この<em>アプリケーションキャッシュ</em>機能を使用しないでください!</strong>これは<a href="https://html.spec.whatwg.org/multipage/browsers.html#offline">ウェブプラットフォームから削除する手続中のものです</a>。</p> - -<ul> - <li>Firefox 84 以降、この機能は削除されました ({{bug("1619673")}})。 Chomium 90 でも削除が予定されており、 Safari でも非推奨になっています。</li> - <li>Firefox 60 以降、および<a href="/ja/docs/Web/HTML/Using_the_application_cache#Browser_compatibility">対応しているブラウザー</a>の一部またはすべてにおいて、<a href="/ja/docs/Web/Security/Secure_Contexts">安全なコンテキスト</a> (HTTPS) でしか利用できません。</li> - <li>Firefox 44 以降ではオフライン対応のために<a href="/ja/docs/Web/HTML/Using_the_application_cache">アプリケーションキャッシュ</a>を使用すると、代わりに<a href="/ja/docs/Web/API/Service_Worker_API/Using_Service_Workers">サービスワーカー</a>を使用するよう開発者に案内する警告メッセージをコンソールに表示します ({{bug("1204581")}})。</li> -</ul> -</div> - -<div>{{DefaultAPISidebar("App Cache")}}{{Deprecated_Header}}{{SecureContext_Header}}</div> - -<h2 id="Introduction" name="Introduction">はじめに</h2> - -<p><a href="/ja/docs/HTML/HTML5">HTML5</a> は、ウェブアプリケーションをオフラインで実行できるようにするための<em>アプリケーションキャッシュ</em>の仕組みを提供しています。この <strong>Application Cache</strong> (<em>AppCache</em>) インターフェイスは、ブラウザーがオフラインで利用できるようにキャッシュするべきリソースを列挙します。キャッシュされたアプリケーションは、ユーザーが更新ボタンを押しても、オフラインで読み込まれて正常に動作します。</p> - -<p>アプリケーションキャッシュは以下のような利益をもたらします。</p> - -<dl> - <dt>オフラインブラウジング</dt> - <dd>オフライン状態であってもユーザーがサイトを閲覧できます。</dd> - <dt>速度</dt> - <dd>キャッシュされたリソースはローカルに置かれることになり、その結果、より速く読み込まれます。</dd> - <dt>サーバー不の削減</dt> - <dd>ブラウザーはサーバーから変更されたリソースのみをダウンロードします。</dd> -</dl> - -<h2 id="How_the_application_cache_works" name="How_the_application_cache_works">アプリケーションキャッシュの動作</h2> - -<h3 id="Enabling_the_application_cache" name="Enabling_the_application_cache">アプリケーションキャッシュの有効化</h3> - -<p>アプリケーションでアプリケーションキャッシュを有効にするには、 {{HTMLAttrxRef("manifest", "html")}} 属性をアプリケーションページ内の {{HTMLElement("html")}} 要素に設定してください。</p> - -<pre class="brush: html notranslate"><html manifest="/example.appcache"> - … -</html> -</pre> - -<p><code>manifest</code> 属性の値は <strong>キャッシュマニフェスト</strong> ファイルの URL を参照します。これはアプリケーションのためにブラウザーがキャッシュするべき URL を列挙したテキストファイルです。</p> - -<p>キャッシュしてほしいサイトのすべてのページに <code>manifest</code> 属性を含めてください。ブラウザーは <code>manifest</code> 属性のないページは、マニフェストファイルで列挙されていない限りキャッシュしません。マニフェストファイルにキャッシュしてほしいページをすべて列挙する必要はありません。なぜなら、ブラウザーは、ユーザーが訪問したページに <code>manifest</code> 属性があると、暗黙的にアプリケーションキャッシュに追加するからです。</p> - -<p>ブラウザーによっては (例: Firefox) は、ユーザーがアプリケーションキャッシュを利用するアプリケーションを読み込む初回時に通知バーを表示します。通知バーは以下のようなメッセージを表示します。</p> - -<p style="margin-left: 40px;">このサイト (<code>example.com</code>) はオフライン作業用データの保存を求めています。 [許可] [このサイトでは保存しない] [今回は保存しない]</p> - -<p>「オフライン(利用可能) アプリケーション」という表現は、ときに、ユーザーがオフライン機能を利用することを許可したアプリケーションを具体的に指すこともあります。</p> - -<h3 id="Loading_documents" name="Loading_documents">文書の読み込み</h3> - -<p>アプリケーションキャッシュの利用は文書を読み込む通常のプロセスを変更します:</p> - -<ul> - <li>アプリケーションキャッシュが存在する場合、ブラウザーは文書を読み込んで、それに関連付けられたリソースをネットワークにアクセスせずにキャッシュから直接取得します。これは文書の読み込み時間をスピードアップさせます。</li> - <li>ブラウザーはキャッシュマニフェストがサーバー上で更新されているかどうかをチェックします。</li> - <li>キャッシュマニフェストが更新されていた場合、ブラウザーはマニフェストの新しいバージョンとそのマニフェスト内に列挙されたリソースをダウンロードします。これはバックグランドで行われ、パフォーマンスに大きな影響を与えません。</li> -</ul> - -<p>文書を読み込み、アプリケーションキャッシュを更新するプロセスの詳細は以下のようになります。</p> - -<ol> - <li>ブラウザーは <code>manifest</code> 属性を含む文書を訪れたとき、アプリケーションキャッシュが存在しなければ、文書を読み込んでから、マニフェストファイルに列挙されたすべてのエントリーを取得して、アプリケーションキャッシュの最初のバージョンを作成します。</li> - <li>その文書へのその後の訪問では、ブラウザーは文書とマニフェストファイルで指定されたその他のリソースを (サーバーからではなく) アプリケーションキャッシュから読み込みます。さらに、ブラウザーは <code><a href="/ja//docs/DOM/window.applicationCache">window.applicationCache</a></code> オブジェクトに <code>checking</code> イベントを送り、適切な HTTP キャッシュ規則に従い、マニフェストファイルを取得します。</li> - <li>マニフェストファイルの現在のキャッシュされたコピーが最新であった場合、ブラウザーは <code>applicationCache</code> オブジェクトに <code>noupdate</code> イベントを送り、更新プロセスは完了します。サーバー上のキャッシュされたリソースを変更する場合、マニフェストファイル自身も変更する必要があることに注意してください。そうすることで、ブラウザーはすべてのリソースを再び取得する必要があることを知ります。</li> - <li>マニフェストファイルが変更<em>されていた</em>場合、マニフェストに列挙されたファイルのすべて、および、 <code><a href="/ja/docs/nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a></code> が呼ばれたことによってキャッシュに追加されたファイルが、適切な HTTP キャッシュ規則に従い、一時キャッシュに取得されます。この一時キャッシュに取得された各ファイル毎に、ブラウザーは <code>applicationCache</code> オブジェクトに <code>progress</code> イベントを送ります。エラーが起こった場合、ブラウザーは <code>error</code> イベントを送り、更新は中止されます。</li> - <li>すべてのファイルが正常に取得されれば、それらは本当のオフラインキャッシュに動的に移動され、<code>applicationCache</code> オブジェクトに <code>cached</code> イベントを送ります。文書は既にキャッシュからブラウザーに読み込まれているので、更新された文書は文書が(手動かプログラムで)再読込されるまで描画されません。</li> -</ol> - -<h2 id="Storage_location_and_clearing_the_offline_cache" name="Storage_location_and_clearing_the_offline_cache">ストレージの場所とオフラインキャッシュをクリアする</h2> - -<p>Chrome では、設定の "閲覧履歴データの消去..." を選択することか、<a class="external">chrome://appcache-internals/</a> を開くことで、オフラインキャッシュをクリアできます。Safari では、設定に、似たような "キャッシュを空にする" がありますが、ブラウザーの再起動も必要になるかもしれません。</p> - -<p>Firefox では、オフラインキャッシュデータは Firefox プロファイルに分割して保存されています。以下が通常のディスクキャッシュです:</p> - -<ul> - <li>Windows Vista/7: <code>C:\Users\<username>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache</code></li> - <li>Mac/Linux: <code>/Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache</code></li> -</ul> - -<p>Firefox では、現在のステータスを <code>about:cache</code> ページ ("Offline cache device" の見出しがある箇所) で調査できます。オフラインキャッシュは ツール -> オプション -> 詳細 -> ネットワーク -> オフラインデータ の "削除..." ボタンを利用して各サイト毎に別々にクリアできます。</p> - -<p>Firefox 11 以前から Firefox 11 まで、ツール -> 最近の履歴を消去、あるいは、ツール -> オプション -> 詳細 -> ネットワーク -> オフラインデータ -> 今すぐ消去 のどちらでもオフラインキャッシュを消せませんでしたが、このバグは修正されました。</p> - -<p>Linux では、設定は Edit > Preferences > Advanced > Network > Offline Web Content and User Data にあります。</p> - -<p><a href="/ja/DOM/Storage#Storage_location_and_clearing_the_data">DOM Storage データをクリアする</a>も参照してください。</p> - -<p>アプリケーションキャッシュはもう利用されない状態にもなり得ます。アプリケーションマニフェストファイルがサーバーーから削除されたとき、ブラウザーはそのマニフェストを利用しているアプリケーションキャッシュをすべて削除し、<code>applicationCache</code> オブジェクトに "obsoleted" イベントを送信します。これはアプリケーションキャッシュの状態を <code>OBSOLETE</code> に設定します。</p> - -<h2 id="The_cache_manifest_file" name="The_cache_manifest_file">キャッシュマニフェストファイル</h2> - -<h3 id="Referencing_a_cache_manifest_file" name="Referencing_a_cache_manifest_file">キャッシュマニフェストファイルを参照する</h3> - -<p>ウェブアプリケーションでの <code>manifest</code> 属性は、キャッシュマニフェストファイルからの相対パスか絶対 URL のどちらかを指定できます。 (絶対 URL はアプリケーションと同一生成元経由でなければなりません)。キャッシュマニフェストファイルはどんなファイル拡張子でもかまいませんが、<code>text/cache-manifest</code> MIME タイプで提供されなければなりません。</p> - -<div class="note"><strong>注: </strong>Apache サーバーでは、マニフェストファイル (.appcache) ファイルを設定するために、ルートディレクトリ又はアプリケーションと同じディレクトリの .htaccess ファイルに <code>AddType text/cache-manifest .appcache</code> を追加します。</div> - -<h3 id="Entries_in_a_cache_manifest_file" name="Entries_in_a_cache_manifest_file">キャッシュマニフェストファイルのエントリー</h3> - -<p>キャッシュマニフェストファイルはブラウザーがオフラインアクセスのためにキャッシュすべきリソースを列挙した単純なテキストファイルです。リソースは URI によって区別されます。キャッシュマニフェストに列挙されたエントリーはマニフェストと同じスキーマ、ホスト、およびポートでなければなりません。</p> - -<h3 id="Example_1_a_simple_cache_manifest_file" name="Example_1_a_simple_cache_manifest_file">例 1: 単純なキャッシュマニフェストファイル</h3> - -<p>以下は、<span class="nowiki">www.example.com</span> にある想像上のウェブサイトのための単純なキャッシュマニフェストファイルである <code>example.appcache です。</code></p> - -<pre class="eval notranslate">CACHE MANIFEST -# v1 - 2011-08-13 -# これはコメントです。 -<span class="nowiki">http://www.example.com/index.html</span> -<span class="nowiki">http://www.example.com/header.png</span> -<span class="nowiki">http://www.example.com/blah/blah</span> -</pre> - -<p>キャッシュマニフェストファイルは3つのセクション (後述する <code>CACHE</code>, <code>NETWORK</code>, <code>FALLBACK</code>) を含んでいます。上記の例では、セクションヘッダーがありません。そのため、すべてのデータ行は明示的 (<code>CACHE</code>) セクションであるとみなされます。これは、ブラウザーは列挙されたリソースのすべてをアプリケーションキャッシュにキャッシュすべきということを意味します。リソースは絶対、もしくは、相対 URL (例:<code>index.html</code>) のどちらかを用いて指定できます。</p> - -<p>上記例での "v1" コメントがあるのには正当な理由があります。ブラウザーがアプリケーションキャッシュを更新するのは、マニフェストファイルがバイト単位で更新されたときだからです。キャッシュされたリソースを変更したとき (例えば、 <code>header.png</code> 画像を新しい画像に差し替えた場合)、ブラウザーにキャッシュの更新が必要であることを知らせるためにマニフェストファイルの内容も変更する必要があります。どんな変更でもマニフェストファイルに対して行うことができますが、バージョン番号を修正することが、おすすめできるベストプラクティスです。</p> - -<div class="warning"><strong>重要:</strong> マニフェストファイル自身をキャッシュマニフェストファイルに指定しないようにしてください。さもなければ、ブラウザーは新しいマニフェストが利用可能であることを知ることがほぼ不可能になるでしょう。</div> - -<h3 id="Sections_in_a_cache_manifest_file_CACHE_NETWORK_and_FALLBACK" name="Sections_in_a_cache_manifest_file_CACHE_NETWORK_and_FALLBACK">キャッシュマニフェストファイルのセクション: <code>CACHE</code>, <code>NETWORK</code>, <code>FALLBACK</code></h3> - -<p>マニフェストには3つの性質が異なるセクション、 <code>CACHE</code>、<code>NETWORK</code>、<code>FALLBACK</code> があります。</p> - -<dl> - <dt><code>CACHE:</code></dt> - <dd>これはキャッシュマニフェストファイルにおけるエントリーの既定のセクションです。<code>CACHE:</code> セクションヘッダー下 (もしくは <code>CACHE MANIFEST</code> の行の直後) に列挙されたファイルは、それらが初回時にダウンロードされた後に明示的にキャッシュされます。</dd> - <dt><code>NETWORK:</code></dt> - <dd><code>キャッシュマニフェストファイルにおける NETWORK</code> セクションヘッダー下に列挙されたファイルは、サーバーーに接続する必要があるホワイトリスト化されたリソースです。ユーザーがオフライン状態であっても、これらのリソースへのリクエストはすべてキャッシュを無視します。ワイルドカードが利用できます。</dd> - <dt><code>FALLBACK:</code></dt> - <dd><code>FALLBACK:</code> セクションは、リソースにアクセス不可能な場合にブラウザーが利用すべき代替ページを指定します。このセクションにおける各エントリーには 2 つの URI を列挙します。具体的には、最初はリソースであり、2 番目は代替リソースです。両方の URL は相対で、マニフェストファイルと同一生成元経由でなければなりません。ワイルドカードが利用できます。</dd> -</dl> - -<p><code>CACHE</code>, <code>NETWORK</code>, <code>FALLBACK</code> の各セクションは、キャッシュマニフェストファイル内でどんな順番でも列挙でき、各セクションは単一のマニフェストにおいて、複数回定義することができます。</p> - -<h3 id="Example_2_a_more_complete_cache_manifest_file" name="Example_2_a_more_complete_cache_manifest_file">例 2: より完全なキャッシュマニフェストファイル</h3> - -<p>以下は、 <span class="nowiki">www.example.com</span> にある想像上のウェブサイト向けのより完全なキャッシュマニフェストファイルです:</p> - -<pre class="eval notranslate">CACHE MANIFEST -# v1 2011-08-14 -# これは別のコメントです -index.html -cache.html -style.css -image1.png - -# 利用可能ならネットワーク経由で利用する -NETWORK: -network.html - -# 代替コンテンツ -FALLBACK: -. fallback.html -</pre> - -<p>この例は <code>NETWORK</code> と <code>FALLBACK</code> セクションを用いて、 <code>network.html</code> ページは常にネットワーク経由で取得し、 <code>fallback.html</code> ページは代替リソース (例えば、サーバーへの接続ができない場合) として提供されるべきであることを指定しています。</p> - -<h3 id="Structure_of_a_cache_manifest_file" name="Structure_of_a_cache_manifest_file">キャッシュマニフェストファイルの構造</h3> - -<p>キャッシュマニフェストファイルは <code>text/cache-manifest</code> という MIME タイプで提供される必要があります。この MIME タイプを使って提供されるすべてのリソースは、このセクションで定義されている、アプリケーションキャッシュマニフェストのための構文に従う必要があります。</p> - -<p>キャッシュマニフェストは UTF-8 形式のテキストファイルで、任意で BOM 文字を含むこともできます。改行文字は、ラインフィード (<code>U+000A</code>)、キャリッジリターン (<code>U+000D</code>)、あるいはその両方で表すことができます。</p> - -<p>キャッシュマニフェストの1行目は、ゼロあるいはそれ以上のスペースまたはタブ文字に続けて「CACHE MANIFEST」という文字列で構成される必要があります。2 つの単語の間にはひとつのスペース (<code>U+0020</code>) が含まれます。1行目に書かれたそれ以外の文字列は無視されます。</p> - -<p>キャッシュマニフェストの残りの部分は、ゼロあるいはそれ以上の、以下の行によって構成されます:</p> - -<dl> - <dt>空白行</dt> - <dd>ゼロあるいはそれ以上のスペースまたはタブ文字から成る空白行を用いることができます。</dd> - <dt>コメント</dt> - <dd>コメントは、ひとつの <code>#</code> 文字に続くゼロあるいはそれ以上のスペースまたはタブ文字と、それに続くゼロあるいはそれ以上のコメント文字列によって構成されます。コメントは (最初の <code>CACHE MANIFEST</code> 行の後の) 単独の行のみで用いることができ、他の行に付加することはできません。これは、フラグメント識別子を指定できないことを意味します。</dd> - <dt>セクションヘッダー</dt> - <dd>セクションヘッダーは、キャッシュマニフェストのどのセクションが操作されるかを示すものです。3種類のセクションヘッダーを用いることができます:</dd> -</dl> - -<blockquote> -<table class="standard-table"> - <tbody> - <tr> - <th>セクションヘッダー</th> - <th>説明</th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td>キャッシュマニフェストの明示的セクションに切り替えます。これは既定のセクションです。</td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td>キャッシュマニフェストのオンラインホワイトリストセクションに切り替えます。</td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td>キャッシュマニフェストの代替セクションに切り替えます。</td> - </tr> - </tbody> -</table> -</blockquote> - -<dl> - <dd>セクションヘッダ行には空白を含めることも可能ですが、セクション名には必ずコロンを含める必要があります。</dd> - <dt>セクションデータ</dt> - <dd>データ行の形式はセクションとごとに異なります。明示的 (<code>CACHE:</code>) セクションでは、各行は、キャッシュのリソースを参照する妥当な URI または IRI です(このセクションではワイルドカード文字は一切利用できません)。各行の URI または IRI の前後には空白を含めることも可能です。 Fallback セクションでは、各行は、リソースと、それに続いて、サーバーとの接続ができないときに提供される代替リソースを参照する妥当な URI または IRI です。ネットワークセクションでは、各行は、ネットワークから取得できるリソースを参照する 妥当な URI または IRI です(このセクションではワイルドカード文字である <code>*</code> が利用できます)。 - <div class="note"><strong>注意: </strong>相対 URI は、マニフェストを参照する文書の URI ではなく、キャッシュマニフェストの URI からの相対となります。</div> - </dd> -</dl> - -<p>キャッシュマニフェストは、それぞれのセクションを任意で行き来することができます (つまり、各セクションヘッダを複数回用いることができます)。また、セクションを空白にしておくことも許容されています。</p> - -<h2 id="Resources_in_an_application_cache" name="Resources_in_an_application_cache">アプリケーションキャッシュ内のリソース</h2> - -<p>アプリケーションキャッシュには、少なくとも 1 つの URI で識別されるリソースが常に含まれています。すべてのリソースは以下のカテゴリのいずれかに当てはまります。</p> - -<dl> - <dt>マスターエントリ</dt> - <dd>これらは、ユーザーが訪問した閲覧コンテキストに、 <code>manifest</code> 属性を使用してこのキャッシュにあることを示す文書が含まれていたためにキャッシュに追加されたリソースです。</dd> - <dt>明示的なエントリ</dt> - <dd>これらはアプリケーションのキャッシュマニフェストファイルに明示的に掲載されているリソースです。</dd> - <dt>ネットワークエントリ</dt> - <dd>これらはアプリケーションのキャッシュマニフェストファイルにネットワークエントリとして掲載されているリソースです。</dd> - <dt>フォールバックエントリ</dt> - <dd>これらはアプリケーションのキャッシュマニフェストファイルにフォールバックエントリとして掲載されているリソースです。</dd> -</dl> - -<div class="note"><strong>注:</strong> リソースは複数のカテゴリでタグ付けすることができるので、複数のエントリに分類することができます。例えば、エントリは明示的なエントリと予備のエントリの両方を持つことができます。</div> - -<p>リソースのカテゴリについては、以下で詳しく説明します。</p> - -<h3 id="Master_entries" name="Master_entries">マスターエントリ</h3> - -<p>マスターエントリとは、 {{HTMLAttrxRef("manifest", "html")}} 属性を {{HTMLElement("html")}} 要素に含む HTML ファイルのことです。例えば、<a href="http://www.example.com/entry.html">http://www.example.com/entry.html</a> という HTML ファイルがあるとします。</p> - -<pre class="brush: html notranslate"><html manifest="example.appcache"> - <h1>アプリケーションキャッシュの例</h1> -</html> -</pre> - -<p><code>entry.html</code> が <code>example.appcache</code> キャッシュマニフェストファイルに掲載されていない場合、 <code>entry.html</code> ページにアクセスすると、 <code>entry.html</code> がマスターエントリとしてアプリケーションキャッシュに追加されます。</p> - -<h3 id="Explicit_entries" name="Explicit_entries">明示的なエントリ</h3> - -<p>明示的なエントリは、キャッシュマニフェストファイルの <code>CACHE</code> セクションに明示的にリストされたリソースです。</p> - -<h3 id="Network_entries" name="Network_entries">ネットワークエントリ</h3> - -<p>キャッシュマニフェストファイルの <code>NETWORK</code> セクションは、ウェブアプリケーションがオンラインアクセスを必要とするリソースを指定します。アプリケーションキャッシュ内のネットワークエントリは本質的に「オンラインホワイトリスト」であり、 <code>NETWORK</code> セクションで指定された URI はキャッシュの代わりにサーバーから読み込まれます。これにより、ブラウザーのセキュリティモデルは、承認されたリソースへのアクセスを制限することで、潜在的なセキュリティ侵害からユーザーを保護することができます。</p> - -<p>例として、ネットワークエントリを使用して、キャッシュの代わりにサーバーからスクリプトなどのコードをロードして実行することができます。</p> - -<pre class="eval notranslate">CACHE MANIFEST -NETWORK: -/api -</pre> - -<p>上記のキャッシュマニフェストセクションは、 <code><a href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> サブツリーに含まれるリソースをロードするリクエストが、キャッシュにアクセスしようとせずに常にネットワークに移動することを保証します。</p> - -<div class="note"><strong>注</strong>: マスターエントリ (<code>html</code> 要素に設定された <code>manifest</code> 属性を持つファイル) をマニフェストファイルから単に省略しても、マスターエントリはアプリケーションキャッシュに追加され、その後アプリケーションキャッシュから提供されるため、同じ結果にはなりません。</div> - -<h3 id="Fallback_entries" name="Fallback_entries">フォールバックエントリ</h3> - -<p>フォールバックエントリは、リソースの読み込みに失敗したときに使用されます。例えば、キャッシュマニフェストファイル <code><a href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> に以下の内容が含まれているとします。</p> - -<pre class="eval notranslate">CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> - -<p><code><a href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code> またはそのサブディレクトリとそのコンテンツへのリクエストにより、ブラウザーはリクエストされたリソースの読み込みを試みるためのネットワークリクエストを発行します。この試みがネットワーク障害や何らかのサーバーエラーのために失敗した場合、ブラウザーは代わりに <code>example.html</code> というファイルをロードします。</p> - -<h2 id="Cache_states" name="Cache_states">キャッシュ状態</h2> - -<p>各アプリケーションキャッシュは、キャッシュの現在の状態を示す<strong>状態</strong>を持っています。同じマニフェスト URI を共有するキャッシュは同じキャッシュの状態を共有します。</p> - -<dl> - <dt><code>UNCACHED</code></dt> - <dd>アプリケーションキャッシュオブジェクトが完全に初期化されていないことを示す特別な値です。</dd> - <dt><code>IDLE</code></dt> - <dd>アプリケーションキャッシュは現在更新中ではありません。</dd> - <dt><code>CHECKING</code></dt> - <dd>マニフェストを取得し、更新をチェックしています。</dd> - <dt><code>DOWNLOADING</code></dt> - <dd>リソースのマニフェストが変更されたため、キャッシュに追加するためにリソースをダウンロードしています。</dd> - <dt><code>UPDATEREADY</code></dt> - <dd>新しいバージョンのアプリケーションキャッシュが利用可能です。対応する <code>updateready</code> イベントがあり、新しい更新プログラムがダウンロードされたが <code>swapCache()</code> メソッドを使用してまだ有効化されていない場合に <code>cached</code> イベントの代わりに発生します。</dd> - <dt><code>OBSOLETE</code></dt> - <dd>アプリケーションキャッシュグループは廃止されました。</dd> -</dl> - -<h2 id="Testing_for_updates_to_the_cache_manifest" name="Testing_for_updates_to_the_cache_manifest">キャッシュマニフェストの更新の確認</h2> - -<p>JavaScript を使用して、アプリケーションが更新されたキャッシュマニフェストファイルを持っているかどうかをプログラムでテストすることができます。スクリプトが更新をテストするためにイベントリスナーをアタッチする前にキャッシュマニフェストファイルが更新されている可能性があるので、スクリプトは常に <code>window.applicationCache.status</code> をテストする必要があります。</p> - -<pre class="brush: js notranslate">function onUpdateReady() { - console.log('found new version!'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> - -<p>新しいマニフェスト ファイルのテストを手動で開始するには、 <code>window.applicationCache.update()</code> を使用してください。</p> - -<h2 id="Gotchas">Gotchas</h2> - -<ul> - <li>従来の GET 引数 (<code>other-cached-page.html?parameterName=value</code>) を使用してキャッシュされたファイルにアクセスしないでください。これは、ブラウザーがキャッシュをバイパスしてネットワークから取得しようとすることになります。 JavaScript で解析されたパラメータを持つキャッシュされたリソースにリンクするには、リンクのハッシュ部分に <code>other-cached-page.html#whatever?parameterName=value</code> のような引数を使用します。</li> - <li>アプリケーションがキャッシュされている場合、ウェブページで使用されるリソース (ファイル) を更新するだけでは、キャッシュされたファイルを更新することはできません。ブラウザーが更新されたファイルを取得して使用する前に、キャッシュマニフェストファイル自体を更新する必要があります。これは <code>window.applicationCache.swapCache()</code> を使用してプログラムで行うことができますが、すでに読み込まれているリソースは影響を受けません。リソースが新しいバージョンのアプリケーションキャッシュから読み込まれるようにするには、ページをリフレッシュするのが理想的です。</li> - <li>ウェブサーバー上で <code>*.appcache</code> ファイルの expires ヘッダを設定して、すぐに期限切れになるようにすることをお勧めします。これにより、マニフェストファイルをキャッシュするリスクを回避することができます。例えば、 Apache ではこのような設定を次のように指定することができます。<br> - <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> - -<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2> - -<div class="hidden">このページの互換性一覧表は構造化データから生成されています。データに協力していただけるのであれば、 <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> をチェックアウトしてプルリクエストを送信してください。</div> - -<p>{{Compat("html.elements.html.manifest")}}</p> - -<h2 id="See_also" name="See_also">関連情報</h2> - -<ul> - <li><a href="https://web.dev/appcache-removal/">Preparing for AppCache Removal</a> - web.dev blog with useful timeline information</li> - <li><a href="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> - <li><a href="http://appcache.offline.technology/">Appcache Facts</a> - detailed information on AppCache idiosyncrasies</li> - <li><a href="https://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Application Cache is a Douchebag</a> - <ul> - <li><a href="https://flailingmonkey.com/application-cache-not-a-douchebag">The Application Cache is no longer a Douchebag</a> - an overview of the app cache debugging tools added in Firefox 23.</li> - </ul> - </li> - <li><a href="https://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li> - <li><a href="https://html.spec.whatwg.org/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> - <li><a href="https://www.w3.org/TR/offline-webapps/">W3C Working Group Note: Offline Web Applications</a></li> - <li><a href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> - <li><a href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a> (IBM developerWorks)</li> - <li><a href="/ja/docs/Application_cache_implementation_overview">アプリケーションキャッシュ実装の概要</a></li> - <li><a href="//www.onlinewebcheck.com/check.php?adv=1">OnlineWebCheck.com - Check cache manifest file syntax</a> (Desktop app for Windows)</li> -</ul> 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 ---- -<div>{{DefaultAPISidebar("App Cache")}}{{SecureContext_Header}}{{Deprecated_Header}} -<div class="blockIndicator warning"> -<p>Using the <em>application caching</em> feature described here is at this point highly discouraged; it’s <a href="https://html.spec.whatwg.org/multipage/browsers.html#offline">in the process of being removed from the Web platform</a>. Use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service Workers</a> instead. In fact as of Firefox 44, when <a href="/en-US/docs/Web/HTML/Using_the_application_cache">AppCache</a> is used to provide offline support for a page a warning message is now displayed in the console advising developers to use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> instead ({{bug("1204581")}}).</p> -</div> -</div> - -<h2 id="소개">소개</h2> - -<p><a href="/en-US/docs/HTML/HTML5" title="HTML/HTML5">HTML5</a> 는 웹기반의 애플리케이션들이 오프라인에서도 실행되도록 해주는 애플리케이션 캐시 메카니즘을 제공한다. 개발자는 브라우저에 캐시되어 오프라인 사용자가 사용할 수 있도록 자원을 지정하기 위하여 애플리케이션 캐시(앱 캐시) 인터페이스를 사용할 수 있다. 캐시된 애플리케이션은 사용자가 오프라인 상태에서 새로고침을 클릭할 때 올바르게 불러와서 작동한다.</p> - -<p>애플리케이션 캐시를 사용하는 것은 애플리케이션에 다음과 같은 이익을 줍니다:</p> - -<ul> - <li>오프라인 브라우징: 유저들은 오프라인에서도 사이트를 탐색할 수 있습니다.</li> - <li>속도: 로컬에 리소스들을 캐싱함으로서, 로딩속도를 향상시킬 수 있습니다.</li> - <li>서버 부하 감소: 브라우저는 서버에서 변경된 리소스들만 다운로드합니다.</li> -</ul> - -<h2 id="애플리케이션_캐시의_작동_방식">애플리케이션 캐시의 작동 방식</h2> - -<h3 id="애플리케이션_캐시_활성화_하기">애플리케이션 캐시 활성화 하기</h3> - -<p>애플리케이션에서 애플리케이션 캐시를 활성화 하기 위해서, 먼저 당신의 애플리케이션의 페이지들의 {{HTMLElement("html")}} 엘리먼트에 {{htmlattrxref("manifest", "html")}} 속성을 추가할 필요가 있습니다:</p> - -<div style="overflow: hidden;"> -<pre class="brush: html"><html manifest="example.appcache"> - ... -</html></pre> -</div> - -<p><code>manifest</code> 속성은 <strong>캐시 매니페스트</strong> 파일을 가르키며, 이는 브라우져가 당신의 애플리케이션을 위해 캐싱할 리소스(파일들)의 리스트인 텍스트 파일입니다.</p> - -<p>당신은 반드시 <code>manifest</code> 속성을 당신 애플리케이션의 캐싱하길 원하는 모든 페이지마다 포함시켜야합니다. The browser does not cache pages that do not contain the <code>manifest</code>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 <code>manifest</code> attribute set to the application cache.</p> - -<p>몇몇 브라우저들은(e.g., Firefox) 애플리케이션 캐시를 사용하는 애플리케이션을 처음 로드할 때 알림을 띄웁니다. 알림은 다음과 같은 메시지를 표시합니다:</p> - -<p style="margin-left: 40px;">해당 사이트가 (<code>www.example.com</code>) 오프라인 사용을 위해 데이터를 저장을 요청합니다. [예] [이 사이트에서 사용안함] [나중에]</p> - -<p>The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities.</p> - -<h3 id="documents_불러오기">documents 불러오기</h3> - -<p>The use of an application cache modifies the normal process of loading a document:</p> - -<ul> - <li>If an application cache exists, the browser loads the document and its associated resources directly from the cache, without accessing the network. This speeds up the document load time.</li> - <li>The browser then checks to see if the cache manifest has been updated on the server.</li> - <li>If the cache manifest has been updated, the browser downloads a new version of the manifest and the resources listed in the manifest. This is done in the background and does not affect performance significantly.</li> -</ul> - -<p>The process for loading documents and updating the application cache is specified in greater detail below:</p> - -<ol> - <li>When the browser visits a document that includes the <code>manifest</code> 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.</li> - <li>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 <code>checking</code> event to the <code><a href="/en-US/docs/DOM/window.applicationCache" title="DOM/window.applicationCache">window.applicationCache</a></code> object, and fetches the manifest file, following the appropriate HTTP caching rules.</li> - <li>If the currently-cached copy of the manifest is up-to-date, the browser sends a <code>noupdate</code> event to the <code>applicationCache</code> 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.</li> - <li>If the manifest file <em>has</em> changed, all the files listed in the manifest—as well as those added to the cache by calling <code><a href="/en-US/docs/nsIDOMOfflineResourceList#add.28.29" title="nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a></code>—are fetched into a temporary cache, following the appropriate HTTP caching rules. For each file fetched into this temporary cache, the browser sends a <code>progress</code> event to the <code>applicationCache</code> object. If any errors occur, the browser sends an <code>error</code> event, and the update halts.</li> - <li>Once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a <code>cached</code> event is sent to the <code>applicationCache</code> 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).</li> -</ol> - -<h2 id="Storage_location_and_clearing_the_offline_cache">Storage location and clearing the offline cache</h2> - -<p>In Chrome you can clear the offline cache by selecting "Clear browsing data..." in the preferences or by visiting <a title="chrome://appcache-internals/">chrome://appcache-internals/</a>. Safari has a similar "Empty cache" setting in its preferences but a browser restart may also be required.</p> - -<p>In Firefox, the offline cache data is stored separately from the Firefox profile—next to the regular disk cache:</p> - -<ul> - <li>Windows Vista/7: <code>C:\Users\<username>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache</code></li> - <li>Mac/Linux: <code>/Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache</code></li> -</ul> - -<p>In Firefox the current status of the offline cache can be inspected on the <code>about:cache</code> page (under the "Offline cache device" heading). The offline cache can be cleared for each site separately using the "Remove..." button in Tools -> Options -> Advanced -> Network -> Offline data.</p> - -<p>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.</p> - -<p>On Linux, you can find the setting at Edit > Preferences > Advanced > Network > Offline Web Content and User Data</p> - -<p>See also <a href="/en-US/docs/DOM/Storage#Storage_location_and_clearing_the_data" title="DOM/Storage#Storage location and clearing the data">clearing the DOM Storage data</a>.</p> - -<p>Application caches can also become obsolete. If an application's manifest file is removed from the server, the browser removes all application caches that use that manifest, and sends an "obsoleted" event to the <code>applicationCache</code> object. This sets the application cache's state to <code>OBSOLETE</code>.</p> - -<h2 id="The_cache_manifest_file">The cache manifest file</h2> - -<h3 id="Referencing_a_cache_manifest_file">Referencing a cache manifest file</h3> - -<p>The <code>manifest</code> 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 <code>text/cache-manifest</code>.</p> - -<div class="note"><strong>Note: </strong>On Apache servers, the MIME type for manifest (.appcache) files can be set by adding <code>AddType text/cache-manifest .appcache</code> to a .htaccess file within either the root directory, or the same directory as the application.</div> - -<h3 id="Entries_in_a_cache_manifest_file">Entries in a cache manifest file</h3> - -<p>The cache manifest file is a simple text file that lists the resources the browser should cache for offline access. Resources are identified by URI. Entries listed in the cache manifest must have the same scheme, host, and port as the manifest.</p> - -<h3 id="Example_1_a_simple_cache_manifest_file">Example 1: a simple cache manifest file</h3> - -<p>The following is a simple cache manifest file, <code>example.appcache</code>, for an imaginary web site at <span class="nowiki">www.example.com</span>.</p> - -<pre>CACHE MANIFEST -# v1 - 2011-08-13 -# This is a comment. -<span class="nowiki">http://www.example.com/index.html</span> -<span class="nowiki">http://www.example.com/header.png</span> -<span class="nowiki">http://www.example.com/blah/blah</span> -</pre> - -<p>A cache manifest file can include three sections (<code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>, discussed below). In the example above, there is no section header, so all data lines are assumed to be in the explicit (<code>CACHE</code>) section, meaning that the browser should cache all the listed resources in the application cache. Resources can be specified using either absolute or relative URLs (e.g., <code>index.html</code>).</p> - -<p>The "v1" comment in the example above is there for a good reason. Browsers only update an application cache when the manifest file changes, byte for byte. If you change a cached resource (for example, you update the <code>header.png</code> image with new content), you must also change the content of the manifest file in order to let browsers know that they need to refresh the cache. You can make any change you want to the manifest file, but revising a version number is the recommended best practice.</p> - -<div class="warning"><strong>Important:</strong> Do not specify the manifest itself in the cache manifest file, otherwise it will be nearly impossible to inform the browser a new manifest is available.</div> - -<h3 id="Sections_in_a_cache_manifest_file_CACHE_NETWORK_and_FALLBACK">Sections in a cache manifest file: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code></h3> - -<p>A manifest can have three distinct sections: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>.</p> - -<dl> - <dt><code>CACHE:</code></dt> - <dd>This is the default section for entries in a cache manifest file. Files listed under the <code>CACHE:</code> section header (or immediately after the <code>CACHE MANIFEST</code> line) are explicitly cached after they're downloaded for the first time.</dd> - <dt><code>NETWORK:</code></dt> - <dd>Files listed under the <code>NETWORK:</code> section header in the cache manifest file are white-listed resources that require a connection to the server. All requests to such resources bypass the cache, even if the user is offline. Wildcards may be used.</dd> - <dt><code>FALLBACK:</code></dt> - <dd>The <code>FALLBACK:</code> section specifies fallback pages the browser should use if a resource is inaccessible. Each entry in this section lists two URIs—the first is the resource, the second is the fallback. Both URIs must be relative and from the same origin as the manifest file. Wildcards may be used.</dd> -</dl> - -<p>The <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK </code>sections can be listed in any order in a cache manifest file, and each section can appear more than once in a single manifest.</p> - -<h3 id="Example_2_a_more_complete_cache_manifest_file">Example 2: a more complete cache manifest file</h3> - -<p>The following is a more complete cache manifest file for the imaginary web site at <span class="nowiki">www.example.com</span>:</p> - -<pre>CACHE MANIFEST -# v1 2011-08-14 -# This is another comment -index.html -cache.html -style.css -image1.png - -# Use from network if available -NETWORK: -network.html - -# Fallback content -FALLBACK: -/ fallback.html -</pre> - -<p>This example uses <code>NETWORK</code> and <code>FALLBACK</code> sections to specify that the <code>network.html</code> page must always be retrieved from the network, and that the <code>fallback.html</code> page should be served as a fallback resource (e.g., in case a connection to the server cannot be established).</p> - -<h3 id="Structure_of_a_cache_manifest_file">Structure of a cache manifest file</h3> - -<p>Cache manifest files must be served with the <code>text/cache-manifest</code> MIME type. All resources served using this MIME type must follow the syntax for an application cache manifest, as defined in this section.</p> - -<p>Cache manifests are UTF-8 format text files, and may optionally include a BOM character. Newlines may be represented by line feed (<code>U+000A</code>), carriage return (<code>U+000D</code>), or carriage return and line feed both.</p> - -<p>The first line of the cache manifest must consist of the string <code>CACHE MANIFEST</code> (with a single <code>U+0020</code> space between the two words), followed by zero or more space or tab characters. Any other text on the line is ignored.</p> - -<p>The remainder of the cache manifest must be comprised of zero or more of the following lines:</p> - -<dl> - <dt>Blank line</dt> - <dd>You may use blank lines comprised of zero or more space and tab characters.</dd> - <dt>Comment</dt> - <dd>Comments consist of zero or more tabs or spaces followed by a single <code>#</code> character, followed by zero or more characters of comment text. Comments may only be used on their own lines (after the initial <span style='font-family: "Courier New","Andale Mono",monospace; font-size: 14px; line-height: normal;'>CACHE MANIFEST </span><span style="font-size: 14px; line-height: 1.572;">line), and cannot be appended to other lines. This means that you cannot specify fragment identifiers.</span></dd> - <dt>Section header</dt> - <dd>Section headers specify which section of the cache manifest is being manipulated. There are three possible section headers:</dd> -</dl> - -<blockquote> -<table class="standard-table"> - <tbody> - <tr> - <th>Section header</th> - <th>Description</th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td>Switches to the explicit section of the cache manifest (this is the default section).</td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td>Switches to the online whitelist section of the cache manifest.</td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td>Switches to the fallback section of the cache manifest.</td> - </tr> - </tbody> -</table> -</blockquote> - -<dl> - <dd>The section header line may include whitespaces, but must include the colon (<code>:</code>) in the section name.</dd> - <dt>Section data</dt> - <dd>The format for lines of data varies from section to section. In the explicit (<code>CACHE:</code>) section, each line is a valid URI or IRI reference to a resource to cache (no wildcard characters are allowed in this sections). Whitespace is allowed before and after the URI or IRI on each line. In the Fallback section each line is a valid URI or IRI reference to a resource, followed by a fallback resource that is to be served up when a connection with the server cannot be made. In the network section, each line is a valid URI or IRI reference to a resource to fetch from the network (the wildcard character * is allowed in this section). - <div class="note"><strong>Note: </strong>Relative URIs are relative to the cache manifest's URI, not to the URI of the document referencing the manifest.</div> - </dd> -</dl> - -<p>Cache manifest files can switch from section to section at will (each section header can be used more than once), and sections are allowed to be empty.</p> - -<h2 id="Resources_in_an_application_cache">Resources in an application cache</h2> - -<p>An application cache always includes at least one resource, identified by URI. All resources fit into one of the following categories:</p> - -<dl> - <dt>Master entries</dt> - <dd>These are resources added to the cache because a browsing context visited by the user included a document that indicated that it was in this cache using its <code>manifest</code> attribute.</dd> - <dt>Explicit entries</dt> - <dd>These are resources explicitly listed in the application's cache manifest file.</dd> - <dt>Network entries</dt> - <dd>These are resources listed in the application's cache manifest files as network entries.</dd> - <dt>Fallback entries</dt> - <dd>These are resources listed in the application's cache manifest files as fallback entries.</dd> -</dl> - -<div class="note"><strong>Note:</strong> 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.</div> - -<p>Resource categories are described in greater detail below.</p> - -<h3 id="Master_entries">Master entries</h3> - -<p>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 <code><a class="linkification-ext external" href="http://www.foo.bar/entry.html" title="Linkification: http://www.foo.bar/entry.html">http://www.example.com/entry.html</a></code>, which looks like this:</p> - -<pre class="brush: html"><html manifest="example.appcache"> - <h1>Application Cache Example</h1> -</html> -</pre> - -<p>If <code>entry.html</code> is not listed in the <code>example.appcache</code> cache manifest file, visiting the <code>entry.html</code> page causes <code>entry.html</code> to be added to the application cache as a master entry.</p> - -<h3 id="Explicit_entries">Explicit entries</h3> - -<p>Explicit entries are resources that are explicitly listed in the <code>CACHE </code>section of a cache manifest file.</p> - -<h3 id="Network_entries">Network entries</h3> - -<p>The <code>NETWORK</code> 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 <code>NETWORK</code> section are loaded from the server instead of the cache. This lets the browser's security model protect the user from potential security breaches by limiting access to approved resources.</p> - -<p>As an example, you can use network entries to load and execute scripts and other code from the server instead of the cache:</p> - -<pre>CACHE MANIFEST -NETWORK: -/api -</pre> - -<p>The cache manifest section listed above ensures that requests to load resources contained in the <code><a href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> subtree always go to the network without attempting to access the cache.</p> - -<div class="note"><strong>Note</strong>: Simply omitting master entries (files that have the <code>manifest</code> attribute set in the <code>html</code> element) from the manifest file would not have the same result, because master entries will be added—and subsequently served from—the application cache.</div> - -<h3 id="Fallback_entries">Fallback entries</h3> - -<p>Fallback entries are used when an attempt to load a resource fails. For example, let's say the cache manifest file <code><a href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> includes the following content:</p> - -<pre>CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> - -<p>Any request to <code><a href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code> 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 <code>example.html</code> instead.</p> - -<h2 id="Cache_states">Cache states</h2> - -<p>Each application cache has a <strong>state</strong>, 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:</p> - -<dl> - <dt><code>UNCACHED</code></dt> - <dd>A special value that indicates that an application cache object is not fully initialized.</dd> - <dt><code>IDLE</code></dt> - <dd>The application cache is not currently in the process of being updated.</dd> - <dt><code>CHECKING</code></dt> - <dd>The manifest is being fetched and checked for updates.</dd> - <dt><code>DOWNLOADING</code></dt> - <dd>Resources are being downloaded to be added to the cache, due to a changed resource manifest.</dd> - <dt><code>UPDATEREADY</code></dt> - <dd>There is a new version of the application cache available. There is a corresponding <code>updateready</code> event, which is fired instead of the <code>cached</code> event when a new update has been downloaded but not yet activated using the <code>swapCache()</code> method.</dd> - <dt><code>OBSOLETE</code></dt> - <dd>The application cache group is now obsolete.</dd> -</dl> - -<h2 id="Testing_for_updates_to_the_cache_manifest">Testing for updates to the cache manifest</h2> - -<p>You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test <code>window.applicationCache.status</code>.</p> - -<pre class="brush: js">function onUpdateReady() { - alert('found new version!'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> - -<p>To manually start testing for a new manifest file, you can use <code>window.applicationCache.update()</code>.</p> - -<h2 id="Gotchas">Gotchas</h2> - -<ul> - <li>Never access cached files by using traditional GET parameters (like <code>other-cached-page.html?parameterName=value</code>). This will make the browser bypass the cache and attempt to get it from network. To link to cached resources that have parameters parsed in JavaScript use parameters in the hash part of the link, such as <code>other-cached-page.html#whatever?parameterName=value</code>.</li> - <li>When applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. You must update the cache manifest file itself before the browser retrieves and uses the updated files. You can do this programmatically using <code>window.applicationCache.swapCache()</code>, though resources that have already been loaded will not be affected. To make sure that resources are loaded from a new version of the application cache, refreshing the page is ideal.</li> - <li>It's a good idea to set expires headers on your web server for <code>*.appcache</code> files to expire immediately. This avoids the risk of caching manifest files. For example, in Apache you can specify such a configuration as follows:<br> - <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> - -<h2 id="브라우저_호환성">브라우저 호환성</h2> - - - -<p>{{Compat("html.elements.html.manifest")}}</p> - -<h2 id="더_알아보기">더 알아보기</h2> - -<ul> - <li><a href="http://www.html5rocks.com/en/tutorials/appcache/beginner/" title="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> - <li><a href="http://appcachefacts.info/" title="http://appcachefacts.info/">appcachefacts.info</a> - detailed information on AppCache idiosyncrasies</li> - <li><a href="http://alistapart.com/article/application-cache-is-a-douchebag" title="http://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Application Cache is a Douchebag</a> - <ul> - <li><a href="http://flailingmonkey.com/application-cache-not-a-douchebag" title="http://flailingmonkey.com/application-cache-not-a-douchebag">The Application Cache is no longer a Douchebag</a> - an overview of the app cache debugging tools added in Firefox 23.</li> - </ul> - </li> - <li><a href="http://hacks.mozilla.org/2010/01/offline-web-applications/" title="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li> - <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> - <li><a href="http://www.w3.org/TR/offline-webapps/" title="http://www.w3.org/TR/offline-webapps/">W3C Working Group Note: Offline Web Applications</a></li> - <li><a href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage" title="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> - <li><a href="http://manifest-validator.com" title="http://manifest-validator.com">Cache Manifest Validator</a></li> - <li>{{interface("nsIApplicationCache")}}</li> - <li>{{interface("nsIApplicationCacheNamespace")}}</li> - <li>{{interface("nsIApplicationCacheContainer")}}</li> - <li>{{interface("nsIApplicationCacheChannel")}}</li> - <li>{{interface("nsIApplicationCacheService")}}</li> - <li>{{interface("nsIDOMOfflineResourceList")}}</li> - <li><a href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a> (IBM developerWorks)</li> - <li><a href="/en-US/docs/Application_cache_implementation_overview" title="/en-US/docs/Application_cache_implementation_overview">Application cache implementation overview</a></li> -</ul> 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 ---- -<p>{{DefaultAPISidebar("App Cache")}}{{deprecated_header}}</p> - -<div class="warning"> -<p>Usar o recurso de <em>application caching</em> descrito aqui é altamente desencorajado nesse momento; ele <a href="https://html.spec.whatwg.org/multipage/browsers.html#offline">está sendo removido da plataforma Web</a>. Em vez dele use <a href="https://developer.mozilla.org/pt-BR/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service Workers</a>. De fato, a partir do Firefox 44, quando o <a href="https://developer.mozilla.org/pt-BR/docs/Web/HTML/Using_the_application_cache">AppCache</a> é usado para prover suporte offline uma mensagem de alerta é exibida no console, recomendando aos desenvolvedores que usem <a href="https://developer.mozilla.org/pt-BR/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> ({{bug("1204581")}}).</p> -</div> - -<h2 id="Introdução">Introdução</h2> - -<p><a href="/en-US/docs/HTML/HTML5" title="HTML/HTML5">HTML5</a> <span>fornece um mecanismo de <em>cache</em> de <em>aplicativo</em> que permite que aplicações baseadas na web sejam executadas offline.</span> <span>Os desenvolvedores podem usar a interface do <strong>cache do aplicativo</strong> <em>(AppCache)</em> para especificar os recursos que o navegador deve armazenar em cache e disponibilizar aos usuários offline.</span> <span>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.</span></p> - -<p><span>Usando um cache de aplicativo dá uma aplicação os seguintes benefícios:</span></p> - -<ul> - <li><span>Navegação off-line: os usuários podem navegar em um site, mesmo quando estão offline.</span></li> - <li><span>Velocidade: os recursos são armazenados em cache local, e, portanto, carregam mais rápido.</span></li> - <li><span>Redução de carga do servidor: o navegador somente faz download de recursos que foram alterados a partir do servidor.</span></li> -</ul> - -<h2 id="Como_funciona_o_cache_de_aplicativo"><span>Como funciona o cache de aplicativo</span></h2> - -<h3 id="Ativando_o_cache_de_aplicativo"><span>Ativando o cache de aplicativo</span></h3> - -<p>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:</p> - -<div> -<pre class="brush: html"><span class="brush: html"><html manifest="example.appcache"> </span> - ... -</html> -</pre> - -<p><span>O atributo manifest faz referência a um arquivo de <strong>manifesto cache,</strong> que é um arquivo de texto que lista os recursos (arquivos) que o navegador deve armazenar em cache para sua aplicação.</span></p> - -<p><span>Você deve incluir o <code>manifest</code> atributo em todas as páginas do seu aplicativo que você deseja armazenar em cache.</span> <span>O navegador não armazena em cache páginas que não contêm o <code>manifest</code> atributo, a menos que tais páginas são explicitamente listados no próprio arquivo de manifesto.</span> <span>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 <code>manifest</code> atributo definido para o cache do aplicativo.</span></p> - -<p><span>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.</span> <span>A barra de notificação exibe uma mensagem como esta:</span></p> - -<p style="margin-left: 40px;">Este site (www.example.com) está pedindo para armazenar dados em seu computador para uso offline. <span>.</span> <span>[Permitir] [Nunca para este Site] [Not Now]</span></p> - -<p>O termo "aplicações (habilitados) offline" às vezes se refere especificamente a aplicativos que o usuário tem permissão para usar recursos offline.</p> - -<h3 id="Carregando_documentos"><span>Carregando documentos</span></h3> - -<p><span>O uso de um cache de aplicação modifica o processo normal de carregamento de um documento:</span></p> - -<ul> - <li><span>Se um cache de aplicativo existe, o navegador carrega o documento e seus recursos associados diretamente a partir do cache, sem acessar a rede.</span><span>Isso acelera o tempo de carregamento do documento.</span></li> - <li><span>O navegador, em seguida, verifica se o manifesto de cache foi atualizado no servidor.</span></li> - <li><span>Se o manifesto de cache foi atualizado, o navegador faz o download de uma nova versão do manifesto e os recursos listados no manifesto.</span> <span>Isto é feito no fundo e não afecta o desempenho significativamente.</span></li> -</ul> - -<p><span>O processo para carregamento de documentos e actualizando o cache de aplicação é especificado em maior detalhe abaixo:</span></p> - -<ol> - <li><span>Quando o navegador visita um documento que inclui o atributo <code>manifest</code>, 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.</span></li> - <li><span>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).</span> <span>Além disso, o navegador também envia uma <code>checking</code> de eventos para o</span> <code><a href="/en-US/docs/DOM/window.applicationCache" title="DOM/window.applicationCache">window.applicationCache</a></code> objeto, e vai buscar o arquivo de manifesto, seguindo as regras de cache HTTP apropriados.</li> - <li><span>Se a cópia atualmente em cache do manifesto é up-to-date, o navegador envia uma <code>noupdate</code> evento ao <code>applicationCache</code> objeto, e o processo de atualização for concluída.</span> <span>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.</span></li> - <li>Se o arquivo de manifesto <em>mudou,</em> todos os arquivos listados no manifesto-bem como aqueles adicionados ao cache chamando <code><a href="/en-US/docs/nsIDOMOfflineResourceList#add.28.29" title="nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a></code>— <span>são buscados em um cache temporário, seguindo as regras de cache HTTP apropriados.</span> <span>Para cada arquivo obtidos para este cache temporário, o navegador envia um <code>progress</code> evento ao <code>applicationCache</code> objeto.</span> <span>Se ocorrer algum erro, o navegador envia um <code>error</code>evento, e a atualização para no meio.</span></li> - <li><span>Depois que todos os arquivos foram recuperados com sucesso, eles são movidos para o cache off-line reais automaticamente, e um <code>cached</code> evento é enviado para o <code>applicationCache</code> objeto.</span> <span>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).</span></li> -</ol> - -<h2 id="Local_de_armazenamento_e_limpando_o_cache_off-line"><span>Local de armazenamento e limpando o cache off-line</span></h2> - -<p>No Chrome, você pode limpar o cache off-line selecionando "Limpar dados de navegação ..." nas preferências ou visitando <a title="chrome://appcache-internals/">chrome://appcache-internals/</a>. Safari tem uma configuração semelhante "cache Empty" em suas preferências, mas uma reinicialização do navegador também pode ser necessária.</p> - -<p>No Firefox, os dados de cache offline é armazenado separadamente a partir do perfil de próxima ao cache de disco regular Firefox:</p> - -<ul> - <li>Windows Vista/7: <code>C:\Users\<username>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache</code></li> - <li>Mac/Linux: <code>/Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache</code></li> -</ul> - -<p><span>No Firefox o status atual do cache off-line pode ser inspecionado no <code>about:cache</code> da página (no âmbito do "dispositivo de cache offline" designação).</span> <span>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.</span></p> - -<p><span>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.</span> <span>Isso foi corrigido.</span></p> - -<p>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</p> - -<p>Veja também <a href="/en-US/docs/DOM/Storage#Storage_location_and_clearing_the_data" title="DOM/Storage#Storage location and clearing the data">a limpeza de dados de armazenamento DOM </a>.</p> - -<p><span>Caches de aplicativos também podem se tornar obsoletos.</span> <span>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 <code>applicationCache</code> objeto.</span> <span>Isso define o estado do cache do aplicativo para <code>OBSOLETE</code> .</span></p> - -<h2 id="O_arquivo_de_manifesto_de_cache"><span>O arquivo de manifesto de cache</span></h2> - -<h3 id="Fazendo_referência_a_um_arquivo_de_manifesto_de_cache"><span>Fazendo referência a um arquivo de manifesto de cache</span></h3> - -<p><span>O <code>manifest</code> atributo em uma aplicação web pode especificar o caminho relativo de um arquivo de manifesto de cache ou um URL absoluto.</span> <span>(Absolute URLs devem ser da mesma origem que a aplicação).</span> <span>Um arquivo de manifesto de cache pode ter qualquer extensão de arquivo, mas ele deve ser servido com o tipo MIME <code>text/cache-manifest</code> .</span></p> - -<div class="note"><strong>Nota: </strong>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.</div> - -<h3 id="As_entradas_de_um_arquivo_de_manifesto_de_cache"><span>As entradas de um arquivo de manifesto de cache</span></h3> - -<p><span>O arquivo de manifesto cache é um simples arquivo de texto que lista os recursos do navegador deve armazenar em cache para acesso offline.</span> <span>Os recursos são identificados pelo URI.</span> <span>Entradas listadas no manifesto de cache deve ter o mesmo esquema, host e porta que o manifesto.</span></p> - -<h3 id="Exemplo_1_um_arquivo_de_manifesto_de_cache_simples"><span>Exemplo 1: um arquivo de manifesto de cache simples</span></h3> - -<p>O que se segue é um arquivo de manifesto de cache simples, <code style="font-style: normal;">example.appcache</code> , para um web site imaginário em <span class="nowiki">www.example.com.</span></p> - -<pre>CACHE MANIFEST -# v1 - 2011-08-13 -# This is a comment. -<span class="nowiki">http://www.example.com/index.html</span> -<span class="nowiki">http://www.example.com/header.png</span> -<span class="nowiki">http://www.example.com/blah/blah</span> -</pre> - -<p><span>Um arquivo de manifesto de cache pode incluir três secções ( <code>CACHE</code> , <code>NETWORK</code> , e <code>FALLBACK</code> , discutidas abaixo).</span> <span>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 ( <code>CACHE</code> seção), o que significa que o navegador deve armazenar em cache todos os recursos listados no cache do aplicativo.</span> <span>Os recursos podem ser especificados usando URLs absoluto ou relativo (por exemplo, <code>index.html</code> ).</span></p> - -<p><span>O comentário "v1" no exemplo acima está lá por um bom motivo.</span> <span>Browsers apenas atualizar um cache de aplicativo quando o arquivo de manifesto muda, byte por byte.</span> <span>Se você alterar um recurso de cache (por exemplo, você atualizar o <code>header.png</code> 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.</span> <span>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.</span></p> - -<div class="warning"><strong>Importante:</strong> 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.</div> - -<h3 id="Seções_em_um_arquivo_de_manifesto_de_cache_CACHE_NETWORK_e_FALLBACK"><span>Seções em um arquivo de manifesto de cache: <code>CACHE</code> , <code>NETWORK</code> , e <code>FALLBACK</code></span></h3> - -<p>Um manifesto pode ter três secções distintas: <code style="font-style: normal;">CACHE</code> , <code style="font-style: normal;">NETWORK</code> , e <code style="font-style: normal;">FALLBACK</code> .</p> - -<dl> - <dt><code>CACHE:</code></dt> - <dd><span>Esta é a seção padrão para entradas em um arquivo de manifesto cache.</span> <span>Os arquivos listados sob o <code>CACHE:</code> cabeçalho de seção (ou imediatamente após o <code>CACHE MANIFEST</code> line) são explicitamente em cache depois do download pela primeira vez.</span></dd> - <dt><code>NETWORK:</code></dt> - <dd><span>Os arquivos listados sob a <code>NETWORK:</code> 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.</span> <span>Todas as solicitações para tais recursos ignorar o cache, mesmo se o usuário estiver offline.</span> <span>O caractere curinga <code>*</code> pode ser usado uma vez.</span> <span>A maioria dos sites precisam <code>*</code> .</span></dd> - <dt><code>FALLBACK:</code></dt> - <dd><span>O <code>FALLBACK:</code> seção especifica páginas fallback o navegador deve usar se um recurso é inacessível.</span> <span>Cada entrada nesta secção enumera duas URIs-o primeiro é o recurso, o segundo é o fallback.</span> <span>Ambos os URIs deve ser relativo e da mesma origem do arquivo de manifesto.</span> <span>Curingas podem ser usados.</span></dd> -</dl> - -<p>Os <code style="font-style: normal;">CACHE</code> , <code style="font-style: normal;">NETWORK</code> e <code style="font-style: normal;">FALLBACK</code> 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.</p> - -<h3 id="Exemplo_2_um_arquivo_de_manifesto_de_cache_mais_completo"><span>Exemplo 2: um arquivo de manifesto de cache mais completo</span></h3> - -<p>O seguinte é um arquivo de manifesto de cache mais completo para o web site imaginário em <span class="nowiki">www.example.com:</span></p> - -<pre>CACHE MANIFEST -# v1 2011-08-14 -# This is another comment -index.html -cache.html -style.css -image1.png - -# Use from network if available -NETWORK: -network.html - -# Fallback content -FALLBACK: -/ fallback.html -</pre> - -<p>Este exemplo usa <code style="font-style: normal;">NETWORK</code> e <code style="font-style: normal;">FALLBACK</code> seções para especificar que o <code style="font-style: normal;">network.html</code> página deve sempre ser recuperada a partir da rede, e que o<code style="font-style: normal;">fallback.html</code> 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 ).</p> - -<h3 id="Estrutura_de_um_arquivo_de_manifesto_de_cache"><span>Estrutura de um arquivo de manifesto de cache</span></h3> - -<p><span>Cache arquivos de manifesto deve ser servido com o <code>text/cache-manifest</code> tipo MIME.</span> <span>Todos os recursos servido usando este tipo MIME deve seguir a sintaxe para um manifesto do cache do aplicativo, conforme definido nesta seção.</span></p> - -<p><span>Manifestos de cache são UTF-8 arquivos de texto formato, e pode incluir, opcionalmente, um personagem BOM.</span> <span>Newlines pode ser representado por avanço de linha ( <code>U+000A</code> ), retorno de carro ( <code>U+000D</code> ), ou retorno de carro e alimentação de linha ambos.</span></p> - -<p><span>A primeira linha do manifesto de cache deve consistir da seqüência de <code>CACHE MANIFEST</code> (com um único <code>U+0020</code> o espaço entre as duas palavras), seguido de zero ou mais espaço ou tabulação caracteres.</span> <span>Qualquer outro texto na linha é ignorado.</span></p> - -<p>O restante do manifesto cache deve ser composta de zero ou mais das seguintes linhas:</p> - -<dl> - <dt><span>Linha em branco</span></dt> - <dd><span>Você pode usar linhas em branco composta de zero ou mais de espaço e caracteres de tabulação.</span></dd> - <dt><span>Comentário</span></dt> - <dd><span>Comentários consistem em zero ou mais abas ou espaços seguidos por um único <code>#</code> caracteres, seguido por zero ou mais caracteres de texto de comentário.</span> <span>Comentários só pode ser utilizado em suas próprias linhas (após a <span style="line-height: 1.572;">linha</span> <span style="font-family: courier new,andale mono,monospace; line-height: normal;">MANIFESTO CACHE</span> <span style="line-height: 1.572;">inicial), e não pode ser adicionado a outras linhas.</span></span> <span><span style="line-height: 1.572;">Isso significa que você não pode especificar identificadores de fragmentos.</span></span></dd> - <dt><span>Cabeçalho da seção</span></dt> - <dd><span>Cabeçalhos de seção especificar qual seção do manifesto cache está sendo manipulado.</span> <span>Há três cabeçalhos de seção possíveis:</span></dd> -</dl> - -<blockquote> -<table class="standard-table"> - <tbody> - <tr> - <th><strong style="background-color: rgba(212, 221, 228, 0.498039); font-family: open sans light,sans-serif; font-weight: bold;">Cabeçalho da seção</strong></th> - <th><strong style="background-color: rgba(212, 221, 228, 0.498039); font-family: open sans light,sans-serif; font-weight: bold;">Descrição</strong></th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td><span style="background-color: rgba(212, 221, 228, 0.14902);">Muda para a seção explícita do manifesto de cache (esta é a seção padrão).</span></td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td><span style="background-color: rgba(212, 221, 228, 0.14902);">Muda para a seção whitelist linha do manifesto de cache.</span></td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td><span style="background-color: rgba(212, 221, 228, 0.14902);">Muda para a seção de fallback do manifesto de cache.</span></td> - </tr> - </tbody> -</table> -</blockquote> - -<dl> - <dd><span>A linha de cabeçalho da seção pode incluir espaços em branco, mas deve incluir os dois pontos ( <code>:</code> ) no nome da seção.</span></dd> - <dt><span>Seção de dados</span></dt> - <dd><span>O formato de linhas de dados varia de uma seção para outra.</span> <span>No explícita ( <code>CACHE:</code> ) 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).</span> <span>Espaços em branco são permitidas antes e depois da URI ou IRI em cada linha.</span> <span>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.</span> <span>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 <code>*</code> pode ser usado nesta seção).</span></dd> - <dd> - <div class="note"><strong>Nota: </strong>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.</div> - </dd> -</dl> - -<p>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.</p> - -<h2 id="Recursos_do_cache_de_aplicativo"><span>Recursos do cache de aplicativo</span></h2> - -<p><span>Um cache de aplicativo inclui sempre pelo menos um recurso, identificado por URI.</span> <span>Todos os recursos se enquadrar em uma das seguintes categorias:</span></p> - -<dl> - <dt><span>Entradas Mestre</span></dt> - <dd><span>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 <code>manifest</code> atributo.</span></dd> - <dt><span>Entradas explícitas</span></dt> - <dd><span>Estes são os recursos expressamente enumeradas no arquivo de manifesto de cache do aplicativo.</span></dd> - <dt><span>Entradas de rede</span></dt> - <dd><span>Estes são os recursos enumerados no cache de arquivos de manifesto do aplicativo como entradas de rede.</span></dd> - <dt><span>Entradas de fallback</span></dt> - <dd><span>Estes são os recursos enumerados no cache de arquivos de manifesto do aplicativo como entradas de fallback.</span></dd> -</dl> - -<div class="note"><strong>Nota:</strong> 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.</div> - -<p>As categorias de recursos são descritos em maior detalhe abaixo.</p> - -<h3 id="Entradas_Mestre"><span>Entradas Mestre</span></h3> - -<p>Entradas Master são todos os arquivos HTML que incluem um {{htmlattrxref("manifest","html")}} em seu atributo {{HTMLElement("html")}} <span> elemento.</span> <span>Por exemplo, vamos dizer que temos o arquivo HTML</span> <code><a class="linkification-ext external" href="http://www.foo.bar/entry.html" title="Linkification: http://www.foo.bar/entry.html">http://www.example.com/entry.html</a></code>, que se parece com isso:</p> - -<pre class="brush: html"><html manifest="example.appcache"> - <h1>Application Cache Example</h1> -</html> -</pre> - -<p>Se <code style="font-style: normal;">entry.html</code> não está listado no <code style="font-style: normal;">example.appcache</code> arquivo de manifesto cache, visitando o <code style="font-style: normal;">entry.html</code> página faz com que <code style="font-style: normal;">entry.html</code> a ser adicionado ao cache de aplicativo como uma entrada de mestre.</p> - -<h3 id="Entradas_explícitas"><span>Entradas explícitas</span></h3> - -<p>Entradas explícitas são recursos que estão listados explicitamente na <code style="font-style: normal;">CACHE</code> seção de um arquivo de manifesto cache.</p> - -<h3 id="Entradas_de_rede"><span>Entradas de rede</span></h3> - -<p><span>A <code>NETWORK</code> seção de um arquivo de manifesto de cache especifica recursos para que uma aplicação web requer acesso online.</span> <span>Entradas de rede em um cache de aplicativo são essencialmente um -URIs "whitelist on-line" especificadas na <code>NETWORK</code> seção são carregados a partir do servidor em vez do cache.</span><span>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.</span></p> - -<p>Como exemplo, você pode usar as entradas de rede para carregar e executar scripts e outros códigos do servidor em vez do cache:</p> - -<pre>CACHE MANIFEST -NETWORK: -/api -</pre> - -<p>A seção manifesto de cache listados acima assegura que os pedidos para carregar recursos contidos no <code><a href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> subtree sempre ir para a rede sem tentar acessar o cache.</p> - -<div class="note"><strong>Nota</strong>: 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.</div> - -<h3 id="Entradas_de_fallback"><span>Entradas de fallback</span></h3> - -<p><span>Entradas de fallback são usados quando uma tentativa de carregar um recurso falhar.</span> <span>Por exemplo, digamos que o arquivo de manifesto de cache</span> <code><a href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> inclui o seguinte conteúdo:</p> - -<pre>CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> - -<p>Qualquer pedido de <code><a href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code> <span>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.</span> <span>Se a tentativa falhar, devido a uma falha de rede ou um erro no servidor de algum tipo, o navegador carrega o arquivo <code>example.html</code>.</span></p> - -<h2 id="Estados_do_cache"><span>Estados do cache</span></h2> - -<p><span>Cada cache de aplicativo tem um <strong>estado,</strong> o que indica a condição atual do cache.</span> <span>Caches que compartilham o mesmo URI manifesto compartilham o mesmo estado de cache, o que pode ser um dos seguintes procedimentos:</span></p> - -<dl> - <dt><code>UNCACHED</code></dt> - <dd>Um valor especial que indica que um objeto de cache do aplicativo não está totalmente inicializado.</dd> - <dt><code>IDLE</code></dt> - <dd>O cache de aplicativo não está neste momento em processo de ser atualizado.</dd> - <dt><code>CHECKING</code></dt> - <dd>O manifesto está sendo buscado e verificado se há atualizações.</dd> - <dt><code>DOWNLOADING</code></dt> - <dd>Os recursos estão sendo baixados para ser adicionado ao cache, devido a um manifesto de recursos alterado.</dd> - <dt><code>UPDATEREADY</code></dt> - <dd><span>Há uma nova versão do cache do aplicativo disponível.</span> <span>Há um correspondente <code>updateready</code> evento, que é acionado em vez do <code>cached</code> de eventos quando uma nova atualização já foi baixado, mas ainda não activado através do <code>swapCache()</code> método.</span></dd> - <dt><code>OBSOLETE</code></dt> - <dd>O grupo de cache do aplicativo é agora obsoleto.</dd> -</dl> - -<h2 id="Testando_se_há_atualizações_para_o_manifesto_de_cache"><span>Testando se há atualizações para o manifesto de cache</span></h2> - -<p><span>Você pode programaticamente testar para ver se um aplicativo tem um arquivo de manifesto cache atualizado, usando JavaScript.</span> <span>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 testar<code>window.applicationCache.status</code> .</span></p> - -<pre class="brush: js">function onUpdateReady() { - alert('found new version!'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> - -<p>Para iniciar manualmente o teste para um novo arquivo de manifesto, você pode usar <code style="font-style: normal;">window.applicationCache.update()</code> .</p> - -<h2 id="Recomendações">Recomendações</h2> - -<ul> - <li><span>Nunca acessar os arquivos armazenados em cache utilizando parâmetros GET tradicionais (como o <code>other-cached-page.html?parameterName=value</code>).</span> <span>Isso fará com que o desvio do cache do navegador e tentar obtê-lo a partir da rede.</span> <span>Para conectar-se a recursos armazenados em cache que têm parâmetros analisados em parâmetros de uso de JavaScript na parte hash da ligação, como <code>other-cached-page.html#whatever?parameterName=value</code> .</span></li> - <li><span>Quando os aplicativos são armazenados em cache, simplesmente atualizar os recursos (arquivos) que são usados em uma página da web não é suficiente para atualizar os arquivos que foram armazenados em cache.</span> <span>É necessário atualizar o arquivo de manifesto de cache em si antes de o navegador recuperar e usar os arquivos atualizados.</span> <span>Você pode fazer isso por meio de programação usando <code>window.applicationCache.swapCache()</code> , embora que os recursos que já foram carregados não serão afetados.</span> <span>Para certificar-se de que os recursos são carregados a partir de uma nova versão do cache do aplicativo, atualizar a página é o ideal.</span></li> - <li><span>É uma boa idéia para definir cabeçalhos expira em seu servidor web para <code>*.appcache</code> arquivos para expirar imediatamente.</span> <span>Isso evita o risco de cache dos arquivos de manifesto.</span> <span>Por exemplo, no Apache é possível especificar uma configuração tal como se segue:</span> <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> - -<h2 id="Compatibilidade_do_navegador"><span>Compatibilidade do navegador</span></h2> - -<div>{{CompatibilityTable}}</div> - -<div> -<div id="compat-desktop"> -<table class="compat-table" style="height: 57px; width: 763px;"> - <tbody> - <tr> - <th>Recurso</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Suporte básico</td> - <td>4.0</td> - <td>{{CompatGeckoDesktop("1.9.1")}}<sup>[1]</sup></td> - <td>10.0</td> - <td>10.6</td> - <td>4.0</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table" style="height: 57px; width: 765px;"> - <tbody> - <tr> - <th>Recurso</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>Firefox OS</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Suporte básico</td> - <td>2.1</td> - <td>{{CompatVersionUnknown}}</td> - <td>1.0.1<sup>[2]</sup></td> - <td>11.0<sup>[3]</sup></td> - <td>11.0</td> - <td>3.2</td> - </tr> - </tbody> -</table> -</div> -</div> - -<div> </div> - -<p>Nota: [1] As versões do Firefox antes de 3,5 ignora as seções da rede e fallback do arquivo de manifesto cache.<br> - [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 <a href="/pt-BR/Apps/Manifest">appcache_path</a>.<br> - [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.</p> - -<h2 id="Veja_também">Veja também</h2> - -<ul> - <li><a href="http://www.html5rocks.com/pt/tutorials/appcache/beginner/" title="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - Um Guia do Iniciante para Usar o Cache da Aplicação</a></li> - <li><a href="https://translate.google.com/translate?hl=en&sl=eu&tl=pt&u=http%3A%2F%2Falistapart.com%2Farticle%2Fapplication-cache-is-a-douchebag" title="http://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Cache de aplicação é um Douchebag</a></li> - <li><a href="https://translate.google.com/translate?hl=en&sl=en&tl=pt&u=https%3A%2F%2Fhacks.mozilla.org%2F2010%2F01%2Foffline-web-applications%2F" title="http://hacks.mozilla.org/2010/01/offline-web-applications/">Mozilla hacks </a>- Demos de aplicativos offline e explanação de como funciona.</li> - <li><a href="https://translate.google.com/translate?hl=en&sl=en&tl=pt&u=https%3A%2F%2Fhtml.spec.whatwg.org%2Fmultipage%2Fbrowsers.html%23offline" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 - Rascunho de Trabalho: Aplicações web offline</a></li> - <li><a href="https://translate.google.com/translate?hl=en&sl=en&tl=pt&u=http%3A%2F%2Fwww.w3.org%2FTR%2Foffline-webapps%2F" title="http://www.w3.org/TR/offline-webapps/">W3C Grupo de Trabalho - Nota: Aplicações web Offline</a></li> - <li><a href="https://translate.google.com/translate?hl=en&sl=en&tl=pt&u=http%3A%2F%2Fdeveloper.teradata.com%2Fblog%2Fjs186040%2F2011%2F11%2Fhtml5-cache-manifest-an-off-label-usage" title="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache do Manifesto: Um uso do Off-label</a></li> - <li><a href="http://manifest-validator.com" title="http://manifest-validator.com">Validador do Manifesto do Cache</a></li> - <li><a href="https://translate.google.com/translate?hl=en&sl=en&tl=pt&u=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Ftopics%2Foffline%2520mobile%2520app%2520example%2F">IBM developerWorks</a> - Diversos artigos relacionados ao cache de aplicação.</li> - <li>{{interface("nsIApplicationCache")}}</li> - <li>{{interface("nsIApplicationCacheNamespace")}}</li> - <li>{{interface("nsIApplicationCacheContainer")}}</li> - <li>{{interface("nsIApplicationCacheChannel")}}</li> - <li>{{interface("nsIApplicationCacheService")}}</li> - <li>{{interface("nsIDOMOfflineResourceList")}}</li> -</ul> - -<div>{{HTML5ArticleTOC}}</div> -</div> 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 ---- -<div>{{DefaultAPISidebar("App Cache")}}{{SecureContext_Header}}{{Deprecated_Header}} -<div class="blockIndicator warning"> -<p>Using the <em>application caching</em> feature described here is at this point highly discouraged; it’s <a href="https://html.spec.whatwg.org/multipage/browsers.html#offline">in the process of being removed from the Web platform</a>. Use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service Workers</a> instead. In fact as of Firefox 44, when <a href="/en-US/docs/Web/HTML/Using_the_application_cache">AppCache</a> is used to provide offline support for a page a warning message is now displayed in the console advising developers to use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> instead ({{bug("1204581")}}).</p> -</div> -</div> - -<h2 id="Introdução">Introdução</h2> - -<p><a href="/en-US/docs/HTML/HTML5">HTML5</a> provides an <em>application caching</em> mechanism that lets web-based applications run offline. Developers can use the <strong>Application Cache</strong> (<em>AppCache</em>) 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.</p> - -<p>Using an application cache gives an application the following benefits:</p> - -<ul> - <li>Offline browsing: users can navigate a site even when they are offline.</li> - <li>Speed: cached resources are local, and therefore load faster.</li> - <li>Reduced server load: the browser only downloads resources that have changed from the server.</li> -</ul> - -<h2 id="Como_é_que_funciona_a_cache_de_aplicação">Como é que funciona a cache de aplicação</h2> - -<h3 id="Ativar_a_cache_de_aplicação">Ativar a cache de aplicação</h3> - -<p>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:</p> - -<pre class="brush: html"><html manifest="example.appcache"> - ... -</html> -</pre> - -<p>The manifest attribute references a <strong>cache manifest</strong> file, which is a text file that lists resources (files) that the browser should cache for your application.</p> - -<p>You should include the <code>manifest</code> attribute on every page of your application that you want cached. The browser does not cache pages that do not contain the <code>manifest</code> 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 <code>manifest</code> attribute set to the application cache.</p> - -<p>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:</p> - -<p style="margin-left: 40px;">This website (<code>www.example.com</code>) is asking to store data on your computer for offline use. [Allow] [Never for This Site] [Not Now]</p> - -<p>The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities.</p> - -<h3 id="Carregar_documentos">Carregar documentos</h3> - -<p>The use of an application cache modifies the normal process of loading a document:</p> - -<ul> - <li>If an application cache exists, the browser loads the document and its associated resources directly from the cache, without accessing the network. This speeds up the document load time.</li> - <li>The browser then checks to see if the cache manifest has been updated on the server.</li> - <li>If the cache manifest has been updated, the browser downloads a new version of the manifest and the resources listed in the manifest. This is done in the background and does not affect performance significantly.</li> -</ul> - -<p>The process for loading documents and updating the application cache is specified in greater detail below:</p> - -<ol> - <li>When the browser visits a document that includes the <code>manifest</code> 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.</li> - <li>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 <code>checking</code> event to the <code><a href="/en-US/docs/DOM/window.applicationCache">window.applicationCache</a></code> object, and fetches the manifest file, following the appropriate HTTP caching rules.</li> - <li>If the currently-cached copy of the manifest is up-to-date, the browser sends a <code>noupdate</code> event to the <code>applicationCache</code> 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.</li> - <li>If the manifest file <em>has</em> changed, all the files listed in the manifest—as well as those added to the cache by calling <code><a href="/en-US/docs/nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a></code>—are fetched into a temporary cache, following the appropriate HTTP caching rules. For each file fetched into this temporary cache, the browser sends a <code>progress</code> event to the <code>applicationCache</code> object. If any errors occur, the browser sends an <code>error</code> event, and the update halts.</li> - <li>Once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a <code>cached</code> event is sent to the <code>applicationCache</code> 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).</li> -</ol> - -<h2 id="Localização_do_armazenamento_e_limpeza_off-line_da_cache">Localização do armazenamento e limpeza off-line da cache</h2> - -<p>In Chrome you can clear the offline cache by selecting "Clear browsing data..." in the preferences or by visiting <a>chrome://appcache-internals/</a>. Safari has a similar "Empty cache" setting in its preferences but a browser restart may also be required.</p> - -<p>In Firefox, the offline cache data is stored separately from the Firefox profile—next to the regular disk cache:</p> - -<ul> - <li>Windows Vista/7: <code>C:\Users\<username>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache</code></li> - <li>Mac/Linux: <code>/Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache</code></li> -</ul> - -<p>In Firefox the current status of the offline cache can be inspected on the <code>about:cache</code> page (under the "Offline cache device" heading). The offline cache can be cleared for each site separately using the "Remove..." button in Tools -> Options -> Advanced -> Network -> Offline data.</p> - -<p>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.</p> - -<p>On Linux, you can find the setting at Edit > Preferences > Advanced > Network > Offline Web Content and User Data</p> - -<p>See also <a href="/en-US/docs/DOM/Storage#Storage_location_and_clearing_the_data">clearing the DOM Storage data</a>.</p> - -<p>Application caches can also become obsolete. If an application's manifest file is removed from the server, the browser removes all application caches that use that manifest, and sends an "obsoleted" event to the <code>applicationCache</code> object. This sets the application cache's state to <code>OBSOLETE</code>.</p> - -<h2 id="O_ficheiro_manifest_da_cache">O ficheiro <em>manifest </em>da cache</h2> - -<h3 id="Referencing_a_cache_manifest_file">Referencing a cache manifest file</h3> - -<p>The <code>manifest</code> 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 <code>text/cache-manifest</code>.</p> - -<div class="note"><strong>Note: </strong>On Apache servers, the MIME type for manifest (.appcache) files can be set by adding <code>AddType text/cache-manifest .appcache</code> to a .htaccess file within either the root directory, or the same directory as the application.</div> - -<h3 id="Entries_in_a_cache_manifest_file">Entries in a cache manifest file</h3> - -<p>The cache manifest file is a simple text file that lists the resources the browser should cache for offline access. Resources are identified by URI. Entries listed in the cache manifest must have the same scheme, host, and port as the manifest.</p> - -<h3 id="Example_1_a_simple_cache_manifest_file">Example 1: a simple cache manifest file</h3> - -<p>The following is a simple cache manifest file, <code>example.appcache</code>, for an imaginary web site at <span class="nowiki">www.example.com</span>.</p> - -<pre class="eval">CACHE MANIFEST -# v1 - 2011-08-13 -# This is a comment. -<span class="nowiki">http://www.example.com/index.html</span> -<span class="nowiki">http://www.example.com/header.png</span> -<span class="nowiki">http://www.example.com/blah/blah</span> -</pre> - -<p>A cache manifest file can include three sections (<code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>, discussed below). In the example above, there is no section header, so all data lines are assumed to be in the explicit (<code>CACHE</code>) section, meaning that the browser should cache all the listed resources in the application cache. Resources can be specified using either absolute or relative URLs (e.g., <code>index.html</code>).</p> - -<p>The "v1" comment in the example above is there for a good reason. Browsers only update an application cache when the manifest file changes, byte for byte. If you change a cached resource (for example, you update the <code>header.png</code> image with new content), you must also change the content of the manifest file in order to let browsers know that they need to refresh the cache. You can make any change you want to the manifest file, but revising a version number is the recommended best practice.</p> - -<div class="warning"><strong>Important:</strong> Do not specify the manifest itself in the cache manifest file, otherwise it will be nearly impossible to inform the browser a new manifest is available.</div> - -<h3 id="Sections_in_a_cache_manifest_file_CACHE_NETWORK_and_FALLBACK">Sections in a cache manifest file: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code></h3> - -<p>A manifest can have three distinct sections: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>.</p> - -<dl> - <dt><code>CACHE:</code></dt> - <dd>This is the default section for entries in a cache manifest file. Files listed under the <code>CACHE:</code> section header (or immediately after the <code>CACHE MANIFEST</code> line) are explicitly cached after they're downloaded for the first time.</dd> - <dt><code>NETWORK:</code></dt> - <dd>Files listed under the <code>NETWORK:</code> 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 <code>*</code> can be used once. Most sites need <code>*</code>.</dd> - <dt><code>FALLBACK:</code></dt> - <dd>The <code>FALLBACK:</code> section specifies fallback pages the browser should use if a resource is inaccessible. Each entry in this section lists two URIs—the first is the resource, the second is the fallback. Both URIs must be relative and from the same origin as the manifest file. Wildcards may be used.</dd> -</dl> - -<p>The <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK </code>sections can be listed in any order in a cache manifest file, and each section can appear more than once in a single manifest.</p> - -<h3 id="Example_2_a_more_complete_cache_manifest_file">Example 2: a more complete cache manifest file</h3> - -<p>The following is a more complete cache manifest file for the imaginary web site at <span class="nowiki">www.example.com</span>:</p> - -<pre class="eval">CACHE MANIFEST -# v1 2011-08-14 -# This is another comment -index.html -cache.html -style.css -image1.png - -# Use from network if available -NETWORK: -network.html - -# Fallback content -FALLBACK: -. fallback.html -</pre> - -<p>This example uses <code>NETWORK</code> and <code>FALLBACK</code> sections to specify that the <code>network.html</code> page must always be retrieved from the network, and that the <code>fallback.html</code> page should be served as a fallback resource (e.g., in case a connection to the server cannot be established).</p> - -<h3 id="Structure_of_a_cache_manifest_file">Structure of a cache manifest file</h3> - -<p>Cache manifest files must be served with the <code>text/cache-manifest</code> MIME type. All resources served using this MIME type must follow the syntax for an application cache manifest, as defined in this section.</p> - -<p>Cache manifests are UTF-8 format text files, and may optionally include a BOM character. Newlines may be represented by line feed (<code>U+000A</code>), carriage return (<code>U+000D</code>), or carriage return and line feed both.</p> - -<p>The first line of the cache manifest must consist of the string <code>CACHE MANIFEST</code> (with a single <code>U+0020</code> space between the two words), followed by zero or more space or tab characters. Any other text on the line is ignored.</p> - -<p>The remainder of the cache manifest must be comprised of zero or more of the following lines:</p> - -<dl> - <dt>Blank line</dt> - <dd>You may use blank lines comprised of zero or more space and tab characters.</dd> - <dt>Comment</dt> - <dd>Comments consist of zero or more tabs or spaces followed by a single <code>#</code> character, followed by zero or more characters of comment text. Comments may only be used on their own lines (after the initial <code>CACHE MANIFEST</code> line), and cannot be appended to other lines. This means that you cannot specify fragment identifiers.</dd> - <dt>Section header</dt> - <dd>Section headers specify which section of the cache manifest is being manipulated. There are three possible section headers:</dd> -</dl> - -<blockquote> -<table class="standard-table"> - <tbody> - <tr> - <th>Secção cabeçalho</th> - <th>Descrição</th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td>Switches to the explicit section of the cache manifest (this is the default section).</td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td>Switches to the online whitelist section of the cache manifest.</td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td>Switches to the fallback section of the cache manifest.</td> - </tr> - </tbody> -</table> -</blockquote> - -<dl> - <dd>The section header line may include whitespaces, but must include the colon (<code>:</code>) in the section name.</dd> - <dt>Dados da secção</dt> - <dd>The format for lines of data varies from section to section. In the explicit (<code>CACHE:</code>) section, each line is a valid URI or IRI reference to a resource to cache (no wildcard characters are allowed in this sections). Whitespace is allowed before and after the URI or IRI on each line. In the Fallback section each line is a valid URI or IRI reference to a resource, followed by a fallback resource that is to be served up when a connection with the server cannot be made. In the network section, each line is a valid URI or IRI reference to a resource to fetch from the network (or the wildcard character <code>*</code> can be used in this section). - <div class="note"><strong>Nota: </strong>Relative URIs are relative to the cache manifest's URI, not to the URI of the document referencing the manifest.</div> - </dd> -</dl> - -<p>Cache manifest files can switch from section to section at will (each section header can be used more than once), and sections are allowed to be empty.</p> - -<h2 id="Recursos_na_cache_de_aplicação">Recursos na cache de aplicação</h2> - -<p>An application cache always includes at least one resource, identified by URI. All resources fit into one of the following categories:</p> - -<dl> - <dt>Master entries</dt> - <dd>These are resources added to the cache because a browsing context visited by the user included a document that indicated that it was in this cache using its <code>manifest</code> attribute.</dd> - <dt>Explicit entries</dt> - <dd>These are resources explicitly listed in the application's cache manifest file.</dd> - <dt>Network entries</dt> - <dd>These are resources listed in the application's cache manifest files as network entries.</dd> - <dt>Fallback entries</dt> - <dd>These are resources listed in the application's cache manifest files as fallback entries.</dd> -</dl> - -<div class="note"><strong>Nota:</strong> 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.</div> - -<p>Resource categories are described in greater detail below.</p> - -<h3 id="Master_entries">Master entries</h3> - -<p>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 <a href="http://www.example.com/entry.html">http://www.example.com/entry.html</a>, which looks like this:</p> - -<pre class="brush: html"><html manifest="example.appcache"> - <h1>Application Cache Example</h1> -</html> -</pre> - -<p>If <code>entry.html</code> is not listed in the <code>example.appcache</code> cache manifest file, visiting the <code>entry.html</code> page causes <code>entry.html</code> to be added to the application cache as a master entry.</p> - -<h3 id="Explicit_entries">Explicit entries</h3> - -<p>Explicit entries are resources that are explicitly listed in the <code>CACHE </code>section of a cache manifest file.</p> - -<h3 id="Network_entries">Network entries</h3> - -<p>The <code>NETWORK</code> 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 <code>NETWORK</code> section are loaded from the server instead of the cache. This lets the browser's security model protect the user from potential security breaches by limiting access to approved resources.</p> - -<p>As an example, you can use network entries to load and execute scripts and other code from the server instead of the cache:</p> - -<pre class="eval">CACHE MANIFEST -NETWORK: -/api -</pre> - -<p>The cache manifest section listed above ensures that requests to load resources contained in the <code><a href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> subtree always go to the network without attempting to access the cache.</p> - -<div class="note"><strong>Note</strong>: Simply omitting master entries (files that have the <code>manifest</code> attribute set in the <code>html</code> element) from the manifest file would not have the same result, because master entries will be added—and subsequently served from—the application cache.</div> - -<h3 id="Fallback_entries">Fallback entries</h3> - -<p>Fallback entries are used when an attempt to load a resource fails. For example, let's say the cache manifest file <code><a href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> includes the following content:</p> - -<pre class="eval">CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> - -<p>Any request to <code><a href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code> 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 <code>example.html</code> instead.</p> - -<h2 id="Estados_da_cache">Estados da cache</h2> - -<p>Each application cache has a <strong>state</strong>, 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:</p> - -<dl> - <dt><code>UNCACHED</code></dt> - <dd>A special value that indicates that an application cache object is not fully initialized.</dd> - <dt><code>IDLE</code></dt> - <dd>The application cache is not currently in the process of being updated.</dd> - <dt><code>CHECKING</code></dt> - <dd>The manifest is being fetched and checked for updates.</dd> - <dt><code>DOWNLOADING</code></dt> - <dd>Resources are being downloaded to be added to the cache, due to a changed resource manifest.</dd> - <dt><code>UPDATEREADY</code></dt> - <dd>There is a new version of the application cache available. There is a corresponding <code>updateready</code> event, which is fired instead of the <code>cached</code> event when a new update has been downloaded but not yet activated using the <code>swapCache()</code> method.</dd> - <dt><code>OBSOLETE</code></dt> - <dd>The application cache group is now obsolete.</dd> -</dl> - -<h2 id="Testing_for_updates_to_the_cache_manifest">Testing for updates to the cache manifest</h2> - -<p>You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test <code>window.applicationCache.status</code>.</p> - -<pre class="brush: js">function onUpdateReady() { - console.log('found new version!'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> - -<p>To manually start testing for a new manifest file, you can use <code>window.applicationCache.update()</code>.</p> - -<h2 id="Gotchas">Gotchas</h2> - -<ul> - <li>Never access cached files by using traditional GET parameters (like <code>other-cached-page.html?parameterName=value</code>). This will make the browser bypass the cache and attempt to get it from network. To link to cached resources that have parameters parsed in JavaScript use parameters in the hash part of the link, such as <code>other-cached-page.html#whatever?parameterName=value</code>.</li> - <li>When applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. You must update the cache manifest file itself before the browser retrieves and uses the updated files. You can do this programmatically using <code>window.applicationCache.swapCache()</code>, though resources that have already been loaded will not be affected. To make sure that resources are loaded from a new version of the application cache, refreshing the page is ideal.</li> - <li>It's a good idea to set expires headers on your web server for <code>*.appcache</code> files to expire immediately. This avoids the risk of caching manifest files. For example, in Apache you can specify such a configuration as follows:<br> - <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> - -<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> - - - -<p>{{Compat("html.elements.html.manifest")}}</p> - -<p><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="font-size: 37.3333px;"><strong>Consultar também</strong></span></font></p> - -<ul> - <li><a href="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> - <li><a href="http://appcache.offline.technology/">Appcache Facts</a> - detailed information on AppCache idiosyncrasies</li> - <li><a href="http://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Application Cache is a Douchebag</a> - <ul> - <li><a href="http://flailingmonkey.com/application-cache-not-a-douchebag">The Application Cache is no longer a Douchebag</a> - an overview of the app cache debugging tools added in Firefox 23.</li> - </ul> - </li> - <li><a href="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li> - <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> - <li><a href="http://www.w3.org/TR/offline-webapps/">W3C Working Group Note: Offline Web Applications</a></li> - <li><a href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> - <li><a href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a> (IBM developerWorks)</li> - <li><a href="/en-US/docs/Application_cache_implementation_overview">Application cache implementation overview</a></li> - <li><a href="//www.onlinewebcheck.com/check.php?adv=1">OnlineWebCheck.com - Check cache manifest file syntax</a> (Desktop app for Windows)</li> -</ul> 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/Использование_кеширования_приложений ---- -<h2 id="Введение">Введение</h2> -<p><a href="/en-US/docs/HTML/HTML5" title="HTML/HTML5">HTML5</a> предоставляет механизм <em>кеширования приложения</em>, позволяющий веб-приложениям работать в автономном режиме. Разработчики теперь могут использовать интерфейс <strong>Кеша приложения</strong> (<em>AppCache</em>), сообщая браузеру, какие из ресурсов браузеру следует закешировать и сделать доступными в режиме офлайн. Закодированные приложения загружаются и работают корректно, даже если пользователь обновляет страницу в тот момент, когда он отключён от сети.</p> -<p>Использование механизма кеширования даёт следующие преимущества:</p> -<ul> - <li>Просмотр страниц в автономном режиме: пользователи могут переходить по сайту даже в режиме офлайн.</li> - <li>Скорость: закешированные ресурсы хранятся на устройстве пользователя и, следовательно, загружаются быстрее.</li> - <li>Уменьшение нагрузки на сервер: браузер загружает с сервера только те ресурсы, которые были изменены.</li> -</ul> -<h2 id="Как_работает_кеш_приложения">Как работает кеш приложения</h2> -<h3 id="Включение_механизма_кеширования">Включение механизма кеширования</h3> -<p>Для включения механизма кеширования приложения вам необходимо включить атрибут {{htmlattrxref("manifest", "html")}} в элемент {{HTMLElement("html")}} на странице вашего приложения, как показано примере ниже:</p> -<div style="overflow: hidden;"> - <pre class="brush: html"><html manifest="example.appcache"> - ... -</html> -</pre> -</div> -<p>Атрибут <code>manifest</code> ссылается на файл <strong>манифеста кеша</strong>, который является текстовым файлом и содержит список ресурсов (файлов), которые браузеру следует закешировать для вашего приложения.</p> -<p>Вам следует включить атрибут <code>manifest</code> в каждую страницу вашего приложения, внутри которой вы хотели бы осуществлять кеширование. Браузер не закеширует страницы, не содержащие атрибута <code>manifest</code>, пока такие страницы не будут явно указаны в файле манифеста. Вам не обязательно перечислять все страницы, которые вы хотите закешировать, в файле манифеста, т.к. браузер неявно добавляет в кеш приложения каждую посещаемую пользователем страницу, где есть атрибут <code>manifest</code>.</p> -<p>Некоторые браузеры (например, Firefox) показывают панель уведомлений , когда пользователь загружает использующее кеш приложение в первый раз. Панель уведомлений может показывать примерно такое сообщение::</p> -<p style="margin-left: 40px;">Этот веб-сайт (<code>www.example.com</code>) запрашивает у вас разрешение на хранение данных для автономной работы на вашем компьютере. [Разрешить] [Никогда для этого сайта] [Не сейчас]</p> -<p>Термин "офлайн(-доступные) приложения" иногда относится конкретно к приложениям, которым пользователь разрешил использовать возможности работы офлайн.</p> -<h3 id="Загрузка_документов">Загрузка документов</h3> -<p>Использование кеша приложений изменяет обычный процесс загрузки документа:</p> -<ul> - <li>Если существует кеш приложения, браузер загружает документ и связанные с ним ресурсы напрямую из кеша без использования сети. Это ускоряет загрузку документа.</li> - <li>Затем браузер проверяет, был ли изменён манифест кеша на стороне сервера.</li> - <li>Если манифест кеша изменён, браузер загружает новую версию манифеста и перечисленных в нём ресурсов. Данные действия происходят в фоновом режиме и почти не влияют на производительность.</li> -</ul> -<p>Ниже приведено более подробное описание процесса загрузки документов и обновления кеша приложения:</p> -<ol> - <li>Когда браузер посещает страницу со включённым атрибутом <code>manifest</code> и кеша приложения не существует, браузер загружает документ, а затем получает все пункты файла манифеста, создавая тем самым первую версию кеша приложения.</li> - <li>Последующие посещения данной страницы приводят к загрузке документа и других ресурсов, указанных в файле манифеста, уже из кеша приложения (не с сервера). К тому же браузер также посылает событие <code>checking</code> объекту <code><a href="/en-US/docs/DOM/window.applicationCache" title="DOM/window.applicationCache">window.applicationCache</a></code> и получает файл манифеста в соответствии с правилами кеширования HTTP.</li> - <li>Если текущая закешированная копия манифеста совпадает со скачанной, браузер посылает событие <code>noupdate</code> объекту <code>applicationCache</code>, завершая процесс обновления. Обратите внимание, если вы изменили закешированные ресурсы на стороне сервера, вам также необходимо изменить и файл манифеста, тем самым давая браузеру знать, какие из ресурсов нужно получить повторно.</li> - <li>Если файл манифеста изменился, то все перечисленные в нём файлы, так же, как и добавленные в кеш с помощью вызова <code><a href="/en-US/docs/nsIDOMOfflineResourceList#add.28.29" title="nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a></code>, попадают во временный кеш с учётом правил кеширования HTTP. Во время обновления каждого файла в этом временном кеше браузер посылает событие <code>progress</code> объекту <code>applicationCache</code>. Если происходит ошибка, браузер посылает событие <code>error</code>, а обновление прекращается.</li> - <li>Как только успешно получены все файлы, они автоматически отправляются в настоящий офлайн-кеш, а объекту <code>applicationCache</code> посылается событие <code>cached</code>. Поскольку документ уже был загружен в браузер из кеша, обновлённый документ не перерисуется, пока страница не будет перезагружена (неважно как, вручную или программно).</li> -</ol> -<h2 id="Место_хранения_и_очистка_офлайн-кеша">Место хранения и очистка офлайн-кеша</h2> -<p>В Chrome офлайн-кеш можно очистить, выбрав «Очистить историю...» в настройках или перейдя на адрес <a title="chrome://appcache-internals/">chrome://appcache-internals/</a>. У Safari также есть похожий пункт «Очистить кеш» в настройках, но для этого также может понадобиться перезапуск браузера.</p> -<p>Firefox хранит данные офлайн-кеша отдельно от профиля — по соседству с обычным дисковым кешем:</p> -<ul> - <li>В Windows Vista/7: <code>C:\Users\<пользователь>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<соль>.<имя профиля>\OfflineCache</code></li> - <li>В Mac/Linux: <code>/Users/<<code>пользователь</code>>/Library/Caches/Firefox/Profiles/<<code>соль</code>>.<<code>имя профиля</code>>/OfflineCache</code></li> -</ul> -<p>Текущее состояние офлайн-кеша в Firefox можно посмотреть на странице <code>about:cache</code> (в разделе «Offline cache device»). Офлайн-кеш можно очистить по отдельности для каждого сайта, используя кнопку «Удалить...» в разделе Инструменты -> Настройки -> Дополнительные -> Сеть -> Автономное содержимое.</p> -<p>До Firefox 11 кеш нельзя было очистить ни кнопкой Инструменты -> Удалить недавнюю историю, ни Инструменты -> Настройки -> Дополнительные -> Сеть -> Автономное содержимое -> Очистить сейчас. Сейчас эта проблема устранена.</p> -<p>В Linux настройки офлайн-кеша можно найти в разделе Инструменты -> Настройки -> Дополнительные -> Сеть -> Автономное содержимое и данные пользователя</p> -<p>Смотрите также <a href="/en-US/docs/DOM/Storage#Storage_location_and_clearing_the_data" title="DOM/Storage#Storage location and clearing the data">очистка данных хранилища DOM</a>.</p> -<p>Также кеши приложения могут устареть. Если с сервера удалить файл манифеста, браузер удалит все кеши, которые были в нём указаны, и пошлёт событие <code>obsoleted</code> объекту <code>applicationCache</code>, что установит состояние кеша в <code>OBSOLETE</code>.</p> -<h2 id="Файл_манифеста_кеша">Файл манифеста кеша</h2> -<h3 id="Ссылки_на_файл_манифеста_кеша">Ссылки на файл манифеста кеша</h3> -<p><code>Атрибут manifest</code> может содержать как относительный путь, так и абсолютный URL (который должен соответствовать принципу единого источника) к файлу манифеста. Файл манифеста кеша может иметь любое расширение, но его MIME- тип должен быть <code>text/cache-manifest</code>.</p> -<div class="note"> - <strong>Примечание: </strong>На серверах Apache MIME-тип файлов манифеста (.appcache) можно настроить, добавив строчку <code>AddType text/cache-manifest .appcache</code> в файл .htaccess в корневой директории или же директории приложения.</div> -<h3 id="Пункты_манифеста_кеша">Пункты манифеста кеша</h3> -<p>Манифест кеша представляет собой обычный текстовый файл, содержащий список ресурсов, которые браузеру следует закешировать для обеспечения автономного доступа. Ресурсы идентифицируются по URI. Объекты, перечисленные в манифесте кеша должны иметь те же протокол, хост и порт, что и сам манифест.</p> -<h3 id="Пример_1_простой_файл_манифеста_кеша">Пример 1: простой файл манифеста кеша</h3> -<p>Ниже приведено содержимое простого файла манифеста кеша для воображаемого веб-сайта <span class="nowiki">www.example.com</span>.</p> -<pre>CACHE MANIFEST -# v1 - 2011-08-13 -# Это комментарий. -<span class="nowiki">http://www.example.com/index.html</span> -<span class="nowiki">http://www.example.com/header.png</span> -<span class="nowiki">http://www.example.com/blah/blah</span> -</pre> -<p>Манифест кеша может включать три секции (<code>CACHE</code>, <code>NETWORK</code> и <code>FALLBACK</code>, которые будут рассмотрены далее). В приведённом примере нет заголовков секций, поэтому предполагается, что все строчки находятся в явной секции <code>CACHE</code>, подразумевая, что все указанные в них ресурсы браузеру следует сохранить в кеше приложения. Ресурсы могут быть указаны с использованием как абсолютных, так и относительных URL (например, <code>index.html</code>).</p> -<p>Для наличия в кеше комментария «v1» есть веские основания. Браузер обновляет кеш приложения, только если изменён файл манифеста, хотя бы один байт в нём. Если вы изменяете закешированный ресурс на стороне сервера, (например, при обновлении содержимого картинки <code>header.png</code>), вы также должны изменить содержимое файла манифеста, тем самым сообщая браузеру, что нужно обновить кеш. Вы можете изменять файл манифеста так, как вам угодно, но лучшие практики рекомендуют использовать изменение номера пересмотра.</p> -<div class="warning"> - - <strong>Важное замечание:</strong> Не указывайте в манифесте ссылку на него самого, в противном случае будет невозможно сообщить браузеру о том, что кеш обновился.</div> -<h3 id="Sections_in_a_cache_manifest_file_CACHE_NETWORK_and_FALLBACK">Sections in a cache manifest file: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code></h3> -<p>A manifest can have three distinct sections: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>.</p> -<dl> - <dt> - <code>CACHE:</code></dt> - <dd> - This is the default section for entries in a cache manifest file. Files listed under the <code>CACHE:</code> section header (or immediately after the <code>CACHE MANIFEST</code> line) are explicitly cached after they're downloaded for the first time.</dd> - <dt> - <code>NETWORK:</code></dt> - <dd> - Files listed under the <code>NETWORK:</code> section header in the cache manifest file are white-listed resources that require a connection to the server. All requests to such resources bypass the cache, even if the user is offline. Wildcards may be used.</dd> - <dt> - <code>FALLBACK:</code></dt> - <dd> - The <code>FALLBACK:</code> section specifies fallback pages the browser should use if a resource is inaccessible. Each entry in this section lists two URIs—the first is the resource, the second is the fallback. Both URIs must be relative and from the same origin as the manifest file. Wildcards may be used.</dd> -</dl> -<p>The <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK </code>sections can be listed in any order in a cache manifest file, and each section can appear more than once in a single manifest.</p> -<h3 id="Example_2_a_more_complete_cache_manifest_file">Example 2: a more complete cache manifest file</h3> -<p>The following is a more complete cache manifest file for the imaginary web site at <span class="nowiki">www.example.com</span>:</p> -<pre>CACHE MANIFEST -# v1 2011-08-14 -# This is another comment -index.html -cache.html -style.css -image1.png - -# Use from network if available -NETWORK: -network.html - -# Fallback content -FALLBACK: -/ fallback.html -</pre> -<p>This example uses <code>NETWORK</code> and <code>FALLBACK</code> sections to specify that the <code>network.html</code> page must always be retrieved from the network, and that the <code>fallback.html</code> page should be served as a fallback resource (e.g., in case a connection to the server cannot be established).</p> -<h3 id="Structure_of_a_cache_manifest_file">Structure of a cache manifest file</h3> -<p>Cache manifest files must be served with the <code>text/cache-manifest</code> MIME type. All resources served using this MIME type must follow the syntax for an application cache manifest, as defined in this section.</p> -<p>Cache manifests are UTF-8 format text files, and may optionally include a BOM character. Newlines may be represented by line feed (<code>U+000A</code>), carriage return (<code>U+000D</code>), or carriage return and line feed both.</p> -<p>The first line of the cache manifest must consist of the string <code>CACHE MANIFEST</code> (with a single <code>U+0020</code> space between the two words), followed by zero or more space or tab characters. Any other text on the line is ignored.</p> -<p>The remainder of the cache manifest must be comprised of zero or more of the following lines:</p> -<dl> - <dt> - Blank line</dt> - <dd> - You may use blank lines comprised of zero or more space and tab characters.</dd> - <dt> - Comment</dt> - <dd> - Comments consist of zero or more tabs or spaces followed by a single <code>#</code> character, followed by zero or more characters of comment text. Comments may only be used on their own lines (after the initial <span style='line-height: normal; font-family: "Courier New", "Andale Mono", monospace; font-size: 14px;'>CACHE MANIFEST </span><span style="line-height: 1.572; font-size: 14px;">line), and cannot be appended to other lines. This means that you cannot specify fragment identifiers.</span></dd> - <dt> - Section header</dt> - <dd> - Section headers specify which section of the cache manifest is being manipulated. There are three possible section headers:</dd> -</dl> -<blockquote> - <table class="standard-table"> - <tbody> - <tr> - <th>Section header</th> - <th>Description</th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td>Switches to the explicit section of the cache manifest (this is the default section).</td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td>Switches to the online whitelist section of the cache manifest.</td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td>Switches to the fallback section of the cache manifest.</td> - </tr> - </tbody> - </table> -</blockquote> -<dl> - <dd> - The section header line may include whitespaces, but must include the colon (<code>:</code>) in the section name.</dd> - <dt> - Section data</dt> - <dd> - The format for lines of data varies from section to section. In the explicit (<code>CACHE:</code>) section, each line is a valid URI or IRI reference to a resource to cache (no wildcard characters are allowed in this sections). Whitespace is allowed before and after the URI or IRI on each line. In the Fallback section each line is a valid URI or IRI reference to a resource, followed by a fallback resource that is to be served up when a connection with the server cannot be made. In the network section, each line is a valid URI or IRI reference to a resource to fetch from the network (the wildcard character * is allowed in this section).<br> - <div class="note"> - <strong>Note: </strong>Relative URIs are relative to the cache manifest's URI, not to the URI of the document referencing the manifest.</div> - </dd> -</dl> -<p>Cache manifest files can switch from section to section at will (each section header can be used more than once), and sections are allowed to be empty.</p> -<h2 id="Resources_in_an_application_cache">Resources in an application cache</h2> -<p>An application cache always includes at least one resource, identified by URI. All resources fit into one of the following categories:</p> -<dl> - <dt> - Master entries</dt> - <dd> - These are resources added to the cache because a browsing context visited by the user included a document that indicated that it was in this cache using its <code>manifest</code> attribute.</dd> - <dt> - Explicit entries</dt> - <dd> - These are resources explicitly listed in the application's cache manifest file.</dd> - <dt> - Network entries</dt> - <dd> - These are resources listed in the application's cache manifest files as network entries.</dd> - <dt> - Fallback entries</dt> - <dd> - These are resources listed in the application's cache manifest files as fallback entries.</dd> -</dl> -<div class="note"> - <strong>Note:</strong> 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.</div> -<p>Resource categories are described in greater detail below.</p> -<h3 id="Master_entries">Master entries</h3> -<p>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 <code><a class="linkification-ext external" href="http://www.foo.bar/entry.html" title="Linkification: http://www.foo.bar/entry.html">http://www.example.com/entry.html</a></code>, which looks like this:</p> -<pre class="brush: html"><html manifest="example.appcache"> - <h1>Application Cache Example</h1> -</html> -</pre> -<p>If <code>entry.html</code> is not listed in the <code>example.appcache</code> cache manifest file, visiting the <code>entry.html</code> page causes <code>entry.html</code> to be added to the application cache as a master entry.</p> -<h3 id="Explicit_entries">Explicit entries</h3> -<p>Explicit entries are resources that are explicitly listed in the <code>CACHE </code>section of a cache manifest file.</p> -<h3 id="Network_entries">Network entries</h3> -<p>The <code>NETWORK</code> 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 <code>NETWORK</code> section are loaded from the server instead of the cache. This lets the browser's security model protect the user from potential security breaches by limiting access to approved resources.</p> -<p>As an example, you can use network entries to load and execute scripts and other code from the server instead of the cache:</p> -<pre>CACHE MANIFEST -NETWORK: -/api -</pre> -<p>The cache manifest section listed above ensures that requests to load resources contained in the <code><a href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> subtree always go to the network without attempting to access the cache.</p> -<div class="note"> - <strong>Note</strong>: Simply omitting master entries (files that have the <code>manifest</code> attribute set in the <code>html</code> element) from the manifest file would not have the same result, because master entries will be added—and subsequently served from—the application cache.</div> -<h3 id="Fallback_entries">Fallback entries</h3> -<p>Fallback entries are used when an attempt to load a resource fails. For example, let's say the cache manifest file <code><a href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> includes the following content:</p> -<pre>CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> -<p>Any request to <code><a href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code> 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 <code>example.html</code> instead.</p> -<h2 id="Cache_states">Cache states</h2> -<p>Each application cache has a <strong>state</strong>, 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:</p> -<dl> - <dt> - <code>UNCACHED</code></dt> - <dd> - A special value that indicates that an application cache object is not fully initialized.</dd> - <dt> - <code>IDLE</code></dt> - <dd> - The application cache is not currently in the process of being updated.</dd> - <dt> - <code>CHECKING</code></dt> - <dd> - The manifest is being fetched and checked for updates.</dd> - <dt> - <code>DOWNLOADING</code></dt> - <dd> - Resources are being downloaded to be added to the cache, due to a changed resource manifest.</dd> - <dt> - <code>UPDATEREADY</code></dt> - <dd> - There is a new version of the application cache available. There is a corresponding <code>updateready</code> event, which is fired instead of the <code>cached</code> event when a new update has been downloaded but not yet activated using the <code>swapCache()</code> method.</dd> - <dt> - <code>OBSOLETE</code></dt> - <dd> - The application cache group is now obsolete.</dd> -</dl> -<h2 id="Testing_for_updates_to_the_cache_manifest">Testing for updates to the cache manifest</h2> -<p>You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test <code>window.applicationCache.status</code>.</p> -<pre class="brush: js">function onUpdateReady() { - alert('found new version!'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> -<p>To manually start testing for a new manifest file, you can use <code>window.applicationCache.update()</code>.</p> -<h2 id="Gotchas">Gotchas</h2> -<ul> - <li>Never access cached files by using traditional GET parameters (like <code>other-cached-page.html?parameterName=value</code>). This will make the browser bypass the cache and attempt to get it from network. To link to cached resources that have parameters parsed in JavaScript use parameters in the hash part of the link, such as <code>other-cached-page.html#whatever?parameterName=value</code>.</li> - <li>When applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. You must update the cache manifest file itself before the browser retrieves and uses the updated files. You can do this programmatically using <code>window.applicationCache.swapCache()</code>, though resources that have already been loaded will not be affected. To make sure that resources are loaded from a new version of the application cache, refreshing the page is ideal.</li> - <li>It's a good idea to set expires headers on your web server for <code>*.appcache</code> files to expire immediately. This avoids the risk of caching manifest files. For example, in Apache you can specify such a configuration as follows:<br> - <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> -<h2 id="Browser_compatibility">Browser compatibility</h2> -<p>{{CompatibilityTable}}</p> -<div id="compat-desktop"> - <table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>4.0</td> - <td>3.5</td> - <td>10.0</td> - <td>10.6</td> - <td>4.0</td> - </tr> - </tbody> - </table> -</div> -<div id="compat-mobile"> - <table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>2.1</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatNo}}</td> - <td>11.0</td> - <td>3.2</td> - </tr> - </tbody> - </table> -</div> -<p>Note: Versions of Firefox prior to 3.5 ignore the <code>NETWORK </code>and <code>FALLBACK </code>sections of the cache manifest file.</p> -<h2 id="See_also">See also</h2> -<ul> - <li><a href="http://www.html5rocks.com/en/tutorials/appcache/beginner/" title="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> - <li><a href="http://appcache.offline.technology/" title="http://appcache.offline.technology/">Appcache Facts</a> - detailed information on AppCache idiosyncrasies</li> - <li><a href="http://alistapart.com/article/application-cache-is-a-douchebag" title="http://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Application Cache is a Douchebag</a> - <ul> - <li><a href="http://flailingmonkey.com/application-cache-not-a-douchebag" title="http://flailingmonkey.com/application-cache-not-a-douchebag">The Application Cache is no longer a Douchebag</a> - an overview of the app cache debugging tools added in Firefox 23.</li> - </ul> - </li> - <li><a href="http://hacks.mozilla.org/2010/01/offline-web-applications/" title="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li> - <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> - <li><a href="http://www.w3.org/TR/offline-webapps/" title="http://www.w3.org/TR/offline-webapps/">W3C Working Group Note: Offline Web Applications</a></li> - <li><a href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage" title="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> - <li><a href="http://manifest-validator.com" title="http://manifest-validator.com">Cache Manifest Validator</a></li> - <li>{{interface("nsIApplicationCache")}}</li> - <li>{{interface("nsIApplicationCacheNamespace")}}</li> - <li>{{interface("nsIApplicationCacheContainer")}}</li> - <li>{{interface("nsIApplicationCacheChannel")}}</li> - <li>{{interface("nsIApplicationCacheService")}}</li> - <li>{{interface("nsIDOMOfflineResourceList")}}</li> - <li><a href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a> (IBM developerWorks)</li> - <li><a href="/en-US/docs/Application_cache_implementation_overview" title="/en-US/docs/Application_cache_implementation_overview">Application cache implementation overview</a></li> -</ul> 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 ---- -<p>{{DefaultAPISidebar("App Cache")}}{{deprecated_header}}</p> - -<div class="warning"> -<p>在此刻使用这里描述的应用程序缓存功能高度不鼓励; 它正在处于从Web平台中被删除的过程。请改用<a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service Workers</a> 代替。事实上,在Firefox 44中,当AppCache用于为页面提供离线支持时,控制台中现在显示一条警告消息,建议开发人员改用 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> 代替 ({{bug(1204581)}})。</p> -</div> - -<h2 id="简介">简介</h2> - -<div><a href="https://developer.mozilla.org/en-US/docs/HTML/HTML5" style="line-height: 21px;" title="HTML/HTML5">HTML5</a> <span style="line-height: inherit;">提供一种</span><span style="line-height: 21px;"> </span><em>应用程序缓存</em><em> </em><span style="line-height: inherit;">机制,使得基于web的应用程序可以离线运行。开发者可以使用 </span><strong style="line-height: 21px;">Application Cache </strong><span style="line-height: 21px;">(</span><em>AppCache</em><span style="line-height: 21px;">) </span><span style="line-height: inherit;">接口设定浏览器</span>应该<span style="line-height: inherit;">缓存的</span>资源<span style="line-height: inherit;">并使得离线</span>用户可用<span style="line-height: inherit;">。 在处于离线状态时,即使用户点击刷新按钮,应用也能正常加载与工作。</span></div> - -<div> -<p>使用应用缓存可以得到以下益处:</p> - -<ul> - <li>离线浏览: 用户可以在离线状态下浏览网站内容。</li> - <li>更快的速度: 因为数据被存储在本地,所以速度会更快。</li> - <li>减轻服务器的负载: 浏览器只会下载在服务器上发生改变的资源。</li> -</ul> - -<h2 id="应用缓存如何工作">应用缓存如何工作</h2> - -<h3 id="启用应用缓存">启用应用缓存</h3> -<span style="line-height: 21px;">若想为应用</span>启用<span style="line-height: 21px;">应用缓存,你需要在应用页面中的 {{HTMLElement("html")}} 元素上增加 </span><span style="line-height: 21px;">{{htmlattrxref("manifest", "html")}} 特性,请看下面的例子:</span></div> - -<div> -<div> -<pre class="eval"><span class="nowiki"><html manifest="example.appcache"> </span> - ... -</html> -</pre> -</div> - -<p>manifest 特性与 <strong>缓存清单(cache manifest) </strong>文件关联,这个文件包含了浏览器需要为你的应用程序缓存的资源(文件)列表。</p> - -<p>你应当在每一个意图缓存的页面上添加 manifest 特性。浏览器不会缓存不带有manifest 特性的页面,除非这个页面已经被写在清单文件内的列表里了。你没有必要添加所有你意图缓存的页面的清单文件,浏览器会暗中将用户访问过的并带有 manifest 特性的所有页面添加进应用缓存中。</p> - -<p>有些浏览器,比如说firefox,当用户首次加载一个需要使用应用缓存的应用时,会显示一个提示栏。提示信息如下:</p> - -<p style="margin-left: 40px;">该站点 (<code>www.example.com</code>) 请求在你的电脑上存储数据以供离线使用。[允许] [对此站点永不允许] [暂时不允许]</p> - -<p>术语 「offline(-enabled) applications」 很多情况下指用户已经允许使用离线存储的程序。</p> - -<h3 id="加载文档">加载文档</h3> - -<div> -<p>application cache的使用会修改文档的加载过程:</p> - -<ul> - <li>如果<span style="line-height: normal;">应用</span>缓存存在,浏览器直接从缓存中加载文档与相关资源,不会访问网络。这会提升文档加载速度。</li> - <li>浏览器检查清单文件列出的资源是否在服务器上被修改。</li> - <li>如果清单文件被更新了, 浏览器会下载新的清单文件和相关的资源。 这都是在后台执行的,基本不会影响到webapp的性能。</li> -</ul> - -<p>下面详细描述了加载文档与更新应用缓存的流程:</p> -</div> - -<ol> - <li>当浏览器访问一个包含 <code>manifest</code> 特性的文档时,如果应用缓存不存在,浏览器会加载文档,然后获取所有在清单文件中列出的文件,生成应用缓存的第一个版本。</li> - <li>对该文档的后续访问会使浏览器直接从应用缓存(而不是服务器)中加载文档与其他在清单文件中列出的资源。此外,浏览器还会向 <code style="font-size: 14px;"><a href="/en/DOM/window.applicationCache" title="en/DOM/window.applicationCache">window.applicationCache</a> 对象发送一个</code> <code>checking</code> 事件,在遵循合适的 HTTP 缓存规则前提下,获取清单文件。</li> - <li>如果当前缓存的清单副本是最新的,浏览器将向 <code style="font-size: 14px;">applicationCache 对象发送一个</code> <code>noupdate</code> 事件,到此,更新过程结束。注意,如果你在服务器修改了任何缓存资源,同时也应该修改清单文件,这样浏览器才能知道它需要重新获取资源。</li> - <li>如果清单文件<em>已经</em>改变,文件中列出的所有文件—也包括通过调用 <code><a href="/en/nsIDOMOfflineResourceList#add.28.29" title="en/nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a> 方法添加到缓存中的那些文件</code>—会被获取并放到一个临时缓存中,遵循适当的 HTTP 缓存规则。对于每个加入到临时缓存中的文件,浏览器会向 <code style="font-size: 14px;">applicationCache 对象发送一个</code> <code>progress</code> 事件。如果出现任何错误,浏览器会发送一个 <code>error</code> 事件,并暂停更新。</li> - <li>一旦所有文件都获取成功,它们会自动移送到真正的离线缓存中,并向 <code style="font-size: 14px;">applicationCache 对象发送一个<font face="Lucida Grande, Lucida Sans Unicode, DejaVu Sans, Lucida, Arial, Helvetica, sans-serif"><span style="line-height: 21px;"> </span></font></code><code>cached</code> 事件。鉴于文档早已经被从缓存加载到浏览器中,所以更新后的文档不会重新渲染,直到页面重新加载(可以手动或通过程序).</li> -</ol> - -<h2 id="存储位置与清除离线缓存">存储位置与清除离线缓存</h2> - -<p>在 Chrome 中,你可以在设置中选择 「清除浏览器数据...」 或访问 <a class="external" title="chrome://appcache-internals/">chrome://appcache-internals/</a> 来清除缓存。Safari 在设置中有一个类似的"清空缓存" 选项,但是需要重启浏览器后才能生效。</p> - -<p>在 Firefox 中,离线缓存数据与 Firefox 配置文件是分开存储的—紧挨着硬盘缓存:</p> - -<ul> - <li>Windows Vista/7: <code>C:\Users\<username>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache</code></li> - <li>Mac/Linux: <code>/Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache</code></li> -</ul> - -<p>在 Firefox 中可以通过访问 <code>about:cache</code> 页面(在「离线缓存设置」标题下)来检查离线缓存的当前状况。 若想单独清除每个网站的离线缓存,可以使用 工具 -> 选项 -> 高级 -> 网络 -> 离线数据中的「删除」按钮。</p> - -<p>在 Firefox 11 之前,无论是 工具 -> 清除近期历史 还是 工具 -> 选项 -> 高级 -> 网络 -> 离线数据 -> 立即清除 都无法清除离线缓存。这个问题已经被修复。(点击 “立即清除” 只是将缓存文件清除掉,并没将缓存清单删除,所以下次载入页面是更新缓存,而非创建缓存,意味着cached和updateready事件触发机制不同,如果想要清除掉缓存清单,只能选中域,然后点击移除)</p> - -<p>另请参阅 <a href="/en/DOM/Storage#Storage_location_and_clearing_the_data" title="en/DOM/Storage#Storage location and clearing the data">清除 DOM 存储数据</a>。</p> - -<div> -<p>应用缓存可以变成废弃的。如果从服务器上移除一个应用的清单文件,浏览器将会清除所有清单中列出的应用缓存,并向 <code>applicationCache</code> 对象发送一个「obsolete」事件。这将使得应用缓存的状态变为 <code>OBSOLETE。</code></p> -</div> - -<h2 id="缓存清单文件">缓存清单文件</h2> - -<h3 id="引用一个缓存清单文件">引用一个缓存清单文件</h3> - -<p>web 应用中的 <code>manifest</code> 特性可以指定为缓存清单文件的相对路径或一个绝对 URL(绝对 URL 必须与应用同源)。缓存清单文件可以使用任意扩展名,但传输它的 MIME 类型必须为 <code>text/cache-manifest。</code></p> - - - -<div class="note"><strong>注意:</strong>在 Apache 服务器上,若要设置适用于清单(.appcache)文件的 MIME 类型,可以向根目录或应用的同级目录下的一个 .htaccess 文件中增加 <code style="font-size: 14px;">AddType text/cache-manifest .appcache</code> 。</div> - - - -<h3 id="缓存清单文件中的记录">缓存清单文件中的记录</h3> - -<p>缓存清单文件是一个纯文本文件,它列出了所有浏览器应该缓存起来的资源,以便能够离线访问。资源使用 URI 来标识。在缓存清单文件中列出的所有记录必须拥有相同的协议、主机名与端口号。</p> - -<h3 id="示例_1:一个简单的缓存清单文件">示例 1:一个简单的缓存清单文件</h3> - -<div> -<p>下面是一个简单的缓存清单文件,<code>example.appcache,适用于一个虚拟的网站 </code><span class="nowiki">www.example.com。</span></p> - -<pre class="eval">CACHE MANIFEST -# v1 - 2011-08-13 -# This is a comment. -<span class="nowiki">http://www.example.com/index.html</span> -<span class="nowiki">http://www.example.com/header.png</span> -<span class="nowiki">http://www.example.com/blah/blah</span> -</pre> - -<p>一个缓存清单文件可以包含三段内容 (<code>CACHE,</code> <code>NETWORK,</code> 和 <code>FALLBACK,</code> 下面详细讨论)。 在上面的例子中,没有段落标题,因此所有数据行都认为是属于显式 (<code>CACHE</code>) 段落,这意味着浏览器应该在应用缓存中缓存所有列出的资源。资源可以使用绝对或者相对 URL 来指定(例如 <code>index.html</code>)。</p> - -<p>上面例子中的注释 「v1」很有必要存在。只有当清单文件发生变化时,浏览器才会去更新应用缓存。如果你要更改缓存资源(比如说,你使用了一张新的 <code>header.png</code> 图片),你必须同时修改清单文件中的内容,以便让浏览器知道它们需要更新缓存。你可以对清单文件做任何改动,但大家都认同的最佳实践则是修正版本号。</p> - -<div class="warning"><strong>重要:</strong>不要在清单文件中指定清单文件本身,否则将无法让浏览器得知清单文件有新版本出现。</div> - -<h3 id="缓存清单文件中的段落:_CACHE,_NETWORK,与_FALLBACK">缓存清单文件中的段落: <code>CACHE,</code> <code>NETWORK,与<font face="Georgia, Times, Times New Roman, serif"> </font></code><code>FALLBACK</code></h3> - -<p>清单文件可以分为三段: <code>CACHE,</code> <code>NETWORK,</code>与 <code>FALLBACK</code>.</p> - -<dl> - <dt><code>CACHE:</code></dt> - <dd>这是缓存文件中记录所属的默认段落。在 <code>CACHE</code><code style="font-size: 14px; line-height: inherit;">: </code><code style="font-size: 14px; line-height: inherit;">段落标题后</code><span style="line-height: inherit;">(或直接跟在 </span><code style="font-size: 14px; line-height: inherit;">CACHE MANIFEST</code><span style="line-height: inherit;"> 行后)列出的文件会在它们第一次下载完毕后缓存起来。</span></dd> - <dt><code>NETWORK:</code></dt> - <dd>在 <code>NETWORK:</code> 段落标题下列出的文件是需要与服务器连接的白名单资源。所有类似资源的请求都会绕过缓存,即使用户处于离线状态。可以使用通配符。</dd> - <dt><code>FALLBACK:</code></dt> - <dd><code>FALLBACK:</code> 段指定了一个后备页面,当资源无法访问时,浏览器会使用该页面。该段落的每条记录都列出两个 URI—第一个表示资源,第二个表示后备页面。两个 URI 都必须使用相对路径并且与清单文件同源。可以使用通配符。</dd> -</dl> - -<p><code>CACHE,</code> <code>NETWORK,</code> 和 <code>FALLBACK 段落可以以任意顺序出现在缓存清单文件中,并且每个段落可以在同一清单文件中出现多次。</code></p> - -<h3 id="示例_2:_一个复杂且完整的缓存清单文件">示例 2: 一个复杂且完整的缓存清单文件</h3> - -<p>下面是一个更加完整的缓存清单文件,适用于一个虚拟的网站 <span class="nowiki">www.example.com:</span></p> - -<pre class="eval">CACHE MANIFEST -# v1 2011-08-14 -# This is another comment -index.html -cache.html -style.css -image1.png - -# Use from network if available -NETWORK: -network.html - -# Fallback content -FALLBACK: -/ fallback.html -</pre> - -<p>该例子使用了 <code>NETWORK</code> 与 <code>FALLBACK</code> 段落,指明了 <code>network.html</code> 页面必须始终从网络获取,<code>fallback.html</code> 页面应该作为后备资源来提供(例如,当无法与服务器建立连接时)。</p> - -<h3 id="缓存清单文件的结构">缓存清单文件的结构</h3> - -<p>缓存清单文件必须以 <code>text/cache-manifest</code> MIME 类型来传输。所有通过 MIME 类型传输的文件必须符合本节中定义的适用于应用缓存清单的语法。</p> - -<p>缓存清单是 UTF-8 格式的文本文件,有可能包含一个 BOM 字符。新行可能使用换行符(<code>U+000A</code>),回车(<code>U+000D</code>),或回车加换行符来表示。</p> - -<p>缓存清单文件的第一行必须包含字符串 <code>CACHE MANIFEST</code> (两个单词间使用一个 <code>U+0020</code> 空白),紧接着是零或多个空白或制表符。本行的其他文本会被忽略。</p> - -<p>缓存清单文件的余下内容必须包含零或多个下面的行:</p> - -<dl> - <dt>空行</dt> - <dd>你可以使用包含零或多个空白与制表符的空行。</dd> - <dt>注释</dt> - <dd>注释包括零或多个制表符或空白字符,紧接着是一个 <code>#</code> 字符,再然后是零或多个注释文本字符。注释只能在所在行起作用,不能追加到其他行上。这意味着你无法使用片段标识符。</dd> - <dt>段落标题</dt> - <dd>段落标题指定了缓存文件即将操作的段落。有三个可选的标题:</dd> -</dl> - -<blockquote> -<table class="standard-table"> - <tbody> - <tr> - <th>段落标题</th> - <th>解释</th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td>切换到缓存清单的显式段落(默认段落)。</td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td>切换到缓存清单的在线白名单段落。</td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td>切换到缓存清单的后备资源段落。</td> - </tr> - </tbody> -</table> -</blockquote> - -<dl> - <dd>段落标题所在的行可以包含空白字符,段落名后的冒号 (<code>:</code>) 不可省略。</dd> - <dt>段落数据</dt> - <dd>不同段落的数据行格式有所不同。在默认 (<code>CACHE:</code>) 段落,每行都是一个合法的 URI 或 IRI ,与一个要缓存的资源相关联(本段落内不允许通配符)。每行的 URI 或 IRI 前后允许出现空白字符。在 Fallback 段落内,每行都是一个合法的 URI 或 IRI(与一个资源关联),紧跟着一个后备资源,用于当无法与服务器建立连接时访问。在 Network 段落内,每行都是一个合法的 URI 或 IRI,关联一个需要通过网络获取的资源(本段落内可以使用通配符 *)。 - <div class="note"><strong>注意:</strong>相对 URI 是指相对于缓存清单的 URI,而不是包含清单的文档的 URI。</div> - </dd> -</dl> - -<p>缓存清单可以在段落内任意切换(每个段落标题可以使用多次),而且段落允许为空。</p> - -<h2 id="一个应用缓存中的资源">一个应用缓存中的资源</h2> - -<p>一个应用缓存至少会包含一个资源,由 URI 指定。所有资源都属于下列类别之一:</p> - -<dl> - <dt>主记录</dt> - <dd>这些资源被加入缓存的原因是:用户浏览的一个上下文中包含一个文档,该文档用 <code>manifest</code> 特性明确指明了它属于该缓存。</dd> - <dt>显式记录</dt> - <dd>这些是在应用缓存清单文件中显式列出的资源。</dd> - <dt>网络记录</dt> - <dd>这些是在应用缓存清单文件中作为网络记录列出的资源。</dd> - <dt>后备记录</dt> - <dd>这些是在应用缓存清单文件中作为后备记录列出的资源。</dd> -</dl> - -<div class="note"><strong>注意:</strong> 资源可以被标记为多个类别,因此可以作为多重记录来分类。例如,一条记录既可以是显式记录,也可以是一条后备记录。</div> - -<p>下面来详细介绍资源类别。</p> - -<h3 id="主记录">主记录</h3> -任意在 {{ HTMLElement("html") }} 元素上包含<span style="line-height: inherit;">一个 {{ htmlattrxref("manifest","html") }} 特性的 HTML 文件都可以是主记录。例如,我们拥有 HTML 文件 </span><code style="font-size: 14px; line-height: inherit;"><a class="linkification-ext external" href="http://www.foo.bar/entry.html" title="Linkification: http://www.foo.bar/entry.html">http://www.example.com/entry.html</a>,它看起来是这样的:</code> - -<pre><html manifest="example.appcache"> - <h1>Application Cache Example</h1> -</html> -</pre> - -<p>如果 <code>entry.html</code> 没有在 <code>example.appcache</code> 缓存清单文件中列出来,那么访问 <code>entry.html</code> 页面会使得 <code>entry.html</code> 作为一条主记录加入到应用缓存中。</p> - -<h3 id="显式记录">显式记录</h3> - -<p>显式记录就是在缓存清单文件的 <code>CACHE 段落显式列出的资源</code>。</p> - -<h3 id="网络记录">网络记录</h3> - -<p>缓存清单文件的 <code>NETWORK</code> 段落指定了 web 应用需要在线访问的资源。一个应用缓存中的网络记录本质上来说是一个「在线白名单」—在 <code>NETWORK</code> 段落指定的 URI 会从服务器而不是缓存加载。这使得浏览器的安全模型通过限制用户让其只访问经过验证的资源来避免潜在的安全漏洞。</p> - -<p>举例来说,你可以使用网络记录来从服务器而不是缓存中加载并执行脚本或其他代码:</p> - -<pre>CACHE MANIFEST -NETWORK: -/api -</pre> - -<p>上面列出的缓存清单段落能够保证对 <code><a class="external" href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> 子目录中资源的请求始终通过网络加载,而不会去访问缓存。</p> - -<div class="note"><strong>注意:</strong> 简单的从清单文件中过滤主记录(在 <code style="font-size: 14px; line-height: inherit;">html 元素中拥有</code><span style="line-height: 1.5em;"> </span><code style="font-size: 14px;">manifest</code><span style="line-height: 1.5em;"> 特性的文件)</span><span style="line-height: 1.5em;">并不会产生同样的结果,因为主记录会被添加到—后续访问的获取也会从—应用缓存中。</span></div> - -<h3 id="后备记录">后备记录</h3> - -<p>当尝试请求资源失败时会使用后备记录。例如,缓存清单文件 <code><a class="external" href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> 包含如下内容:</p> - -<pre>CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> - -<p>任何访问 <code><a class="external" href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code> 或它的任意子目录及内容都会使浏览器发出请求,去尝试加载请求的资源。如果尝试失败(可能是由于网络连接失败或服务器问题),浏览器将会加载 <code>example.html。</code></p> - -<h2 id="缓存状态">缓存状态</h2> - -<p>每个应用缓存都有一个<strong>状态</strong>,标示着缓存的当前状况。共享同一清单 URI 的缓存拥有相同的缓存状态,可能是其中之一:</p> - -<dl> - <dt><code>UNCACHED(未缓存)</code></dt> - <dd>一个特殊的值,用于表明一个应用缓存对象还没有完全初始化。</dd> - <dt><code>IDLE(空闲)</code></dt> - <dd>应用缓存此时未处于更新过程中。</dd> - <dt><code>CHECKING(检查)</code></dt> - <dd>清单已经获取完毕并检查更新。</dd> - <dt><code>DOWNLOADING(下载中)</code></dt> - <dd>下载资源并准备加入到缓存中,这是由于清单变化引起的。</dd> - <dt><code>UPDATEREADY(更新就绪)</code></dt> - <dd>一个新版本的应用缓存可以使用。有一个对应的事件 <code>updateready</code>,当下载完毕一个更新,并且还未使用 <code style="font-size: 14px; line-height: inherit;">swapCache() 方法激活更新时,该事件触发,而不会是</code><span style="line-height: inherit;"> </span><code style="font-size: 14px; line-height: inherit;">cached</code><span style="line-height: inherit;"> 事件。</span></dd> - <dt><code>OBSOLETE(废弃)</code></dt> - <dd>应用缓存现在被废弃。</dd> -</dl> - -<h2 id="测试缓存清单的更新">测试缓存清单的更新</h2> - -<p>你可以使用 JavaScript 来写程序检测应用是否拥有一个可以更新的缓存清单文件。因为缓存清单文件可能会在脚本添加事件前完成更新,所以脚本应该始终检测 <code>window.applicationCache.status。</code></p> - -<pre class="brush: js">function onUpdateReady() { - alert('found new version!'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> - -<p> 若要手动测试一个新的清单文件,你可以使用 <code>window.applicationCache.update()。</code></p> - -<h2 id="陷阱">陷阱</h2> - -<ul> - <li>永远不要使用传统 GET 参数(例如 <code>other-cached-page.html?parameterName=value</code>) 来访问缓存文件。这会使浏览器绕过缓存,直接从网络获取。若想链接一个参数需要在 JavaScript 中解析的资源,你可以将参数放到链接的 hash 部分,例如 <code>other-cached-page.html#whatever?parameterName=value。</code></li> - <li>当应用被缓存后,仅仅更新在 web 页面中使用的资源(文件)还不足以更新被缓存的文件。你需要在浏览器获取和使用更新的文件前,去更新缓存清单文件本身。你可以使用 <code>window.applicationCache.swapCache() 以编程的方式完成上述目的,虽然这无法影响到已经加载完毕的资源。为了保证资源从应用缓存的最新版本中加载,最理想的办法就是刷新页面</code>。</li> - <li>通过在 web 服务器上设置 expires header 来使 <code>*.appcache</code> 文件立即过期是个好主意。这避免了将清单文件缓存的风险。例如,在 Apache 中,你可以指定下面的配置项:<br> - <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> - -<h2 id="浏览器兼容性">浏览器兼容性</h2> - -<p>{{ CompatibilityTable() }}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>4.0</td> - <td>3.5</td> - <td>10.0</td> - <td>10.6</td> - <td>4.0</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>2.1</td> - <td>{{ CompatUnknown() }}</td> - <td>{{ CompatNo() }}</td> - <td>11.0</td> - <td>3.2</td> - </tr> - </tbody> -</table> -</div> - -<p>注意:Firefox 3.5 之前的版本会忽略缓存清单文件中的 <code>NETWORK 和</code> <code>FALLBACK 段落。</code></p> - -<h2 id="另见">另见</h2> - -<ul> - <li><a href="http://manifest-validator.com/">Cache Manifest Validator</a></li> - <li><a href="https://www.onlinewebcheck.com/check.php?adv=1">OnlineWebCheck.com - Check cache manifest file syntax</a></li> - <li><a href="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> - <li><a href="http://appcache.offline.technology/">Appcache Facts</a> - detailed information on AppCache idiosyncrasies</li> - <li><a href="http://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Application Cache is a Douchebag</a> - <ul> - <li><a href="http://flailingmonkey.com/application-cache-not-a-douchebag">The Application Cache is no longer a Douchebag</a> - an overview of the app cache debugging tools added in Firefox 23.</li> - </ul> - </li> - <li><a href="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li> - <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> - <li><a href="http://www.w3.org/TR/offline-webapps/">W3C Working Group Note: Offline Web Applications</a></li> - <li><a href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> - <li><a href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a> (IBM developerWorks)</li> - <li><a href="https://developer.mozilla.org/en-US/docs/Application_cache_implementation_overview">Application cache implementation overview</a></li> -</ul> - - -</div> -</div> 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 ---- -<div>{{DefaultAPISidebar("App Cache")}}{{deprecated_header}}</div> - -<div class="warning"> -<p>Using the <em>application caching</em> feature described here is at this point highly discouraged; it’s <a href="https://html.spec.whatwg.org/multipage/browsers.html#offline">in the process of being removed from the Web platform</a>. Use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service Workers</a> instead. In fact as of Firefox 44, when <a href="/en-US/docs/Web/HTML/Using_the_application_cache">AppCache</a> is used to provide offline support for a page a warning message is now displayed in the console advising developers to use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> instead ({{bug("1204581")}}).</p> -</div> - -<h2 id="Introduction">Introduction</h2> - -<p><a href="/en-US/docs/HTML/HTML5">HTML5</a> provides an <em>application caching</em> mechanism that lets web-based applications run offline. Developers can use the <strong>Application Cache</strong> (<em>AppCache</em>) 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.</p> - -<p>Using an application cache gives an application the following benefits:</p> - -<ul> - <li>Offline browsing: users can navigate a site even when they are offline.</li> - <li>Speed: cached resources are local, and therefore load faster.</li> - <li>Reduced server load: the browser only downloads resources that have changed from the server.</li> -</ul> - -<h2 id="How_the_application_cache_works">How the application cache works</h2> - -<h3 id="Enabling_the_application_cache">Enabling the application cache</h3> - -<p>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:</p> - -<pre class="brush: html"><html manifest="example.appcache"> - ... -</html> -</pre> - -<p>The manifest attribute references a <strong>cache manifest</strong> file, which is a text file that lists resources (files) that the browser should cache for your application.</p> - -<p>You should include the <code>manifest</code> attribute on every page of your application that you want cached. The browser does not cache pages that do not contain the <code>manifest</code> 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 <code>manifest</code> attribute set to the application cache.</p> - -<p>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:</p> - -<p style="margin-left: 40px;">This website (<code>www.example.com</code>) is asking to store data on your computer for offline use. [Allow] [Never for This Site] [Not Now]</p> - -<p>The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities.</p> - -<h3 id="Loading_documents">Loading documents</h3> - -<p>The use of an application cache modifies the normal process of loading a document:</p> - -<ul> - <li>If an application cache exists, the browser loads the document and its associated resources directly from the cache, without accessing the network. This speeds up the document load time.</li> - <li>The browser then checks to see if the cache manifest has been updated on the server.</li> - <li>If the cache manifest has been updated, the browser downloads a new version of the manifest and the resources listed in the manifest. This is done in the background and does not affect performance significantly.</li> -</ul> - -<p>The process for loading documents and updating the application cache is specified in greater detail below:</p> - -<ol> - <li>When the browser visits a document that includes the <code>manifest</code> 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.</li> - <li>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 <code>checking</code> event to the <code><a href="/en-US/docs/DOM/window.applicationCache">window.applicationCache</a></code> object, and fetches the manifest file, following the appropriate HTTP caching rules.</li> - <li>If the currently-cached copy of the manifest is up-to-date, the browser sends a <code>noupdate</code> event to the <code>applicationCache</code> 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.</li> - <li>If the manifest file <em>has</em> changed, all the files listed in the manifest—as well as those added to the cache by calling <code><a href="/en-US/docs/nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a></code>—are fetched into a temporary cache, following the appropriate HTTP caching rules. For each file fetched into this temporary cache, the browser sends a <code>progress</code> event to the <code>applicationCache</code> object. If any errors occur, the browser sends an <code>error</code> event, and the update halts.</li> - <li>Once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a <code>cached</code> event is sent to the <code>applicationCache</code> 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).</li> -</ol> - -<h2 id="Storage_location_and_clearing_the_offline_cache">Storage location and clearing the offline cache</h2> - -<p>In Chrome you can clear the offline cache by selecting "Clear browsing data..." in the preferences or by visiting <a>chrome://appcache-internals/</a>. Safari has a similar "Empty cache" setting in its preferences but a browser restart may also be required.</p> - -<p>In Firefox, the offline cache data is stored separately from the Firefox profile—next to the regular disk cache:</p> - -<ul> - <li>Windows Vista/7: <code>C:\Users\<username>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache</code></li> - <li>Mac/Linux: <code>/Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache</code></li> -</ul> - -<p>In Firefox the current status of the offline cache can be inspected on the <code>about:cache</code> page (under the "Offline cache device" heading). The offline cache can be cleared for each site separately using the "Remove..." button in Tools -> Options -> Advanced -> Network -> Offline data.</p> - -<p>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.</p> - -<p>On Linux, you can find the setting at Edit > Preferences > Advanced > Network > Offline Web Content and User Data</p> - -<p>See also <a href="/en-US/docs/DOM/Storage#Storage_location_and_clearing_the_data">clearing the DOM Storage data</a>.</p> - -<p>Application caches can also become obsolete. If an application's manifest file is removed from the server, the browser removes all application caches that use that manifest, and sends an "obsoleted" event to the <code>applicationCache</code> object. This sets the application cache's state to <code>OBSOLETE</code>.</p> - -<h2 id="The_cache_manifest_file">The cache manifest file</h2> - -<h3 id="Referencing_a_cache_manifest_file">Referencing a cache manifest file</h3> - -<p>The <code>manifest</code> 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 <code>text/cache-manifest</code>.</p> - -<div class="note"><strong>Note: </strong>On Apache servers, the MIME type for manifest (.appcache) files can be set by adding <code>AddType text/cache-manifest .appcache</code> to a .htaccess file within either the root directory, or the same directory as the application.</div> - -<h3 id="Entries_in_a_cache_manifest_file">Entries in a cache manifest file</h3> - -<p>The cache manifest file is a simple text file that lists the resources the browser should cache for offline access. Resources are identified by URI. Entries listed in the cache manifest must have the same scheme, host, and port as the manifest.</p> - -<h3 id="Example_1_a_simple_cache_manifest_file">Example 1: a simple cache manifest file</h3> - -<p>The following is a simple cache manifest file, <code>example.appcache</code>, for an imaginary web site at <span class="nowiki">www.example.com</span>.</p> - -<pre class="eval">CACHE MANIFEST -# v1 - 2011-08-13 -# This is a comment. -<span class="nowiki">http://www.example.com/index.html</span> -<span class="nowiki">http://www.example.com/header.png</span> -<span class="nowiki">http://www.example.com/blah/blah</span> -</pre> - -<p>A cache manifest file can include three sections (<code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>, discussed below). In the example above, there is no section header, so all data lines are assumed to be in the explicit (<code>CACHE</code>) section, meaning that the browser should cache all the listed resources in the application cache. Resources can be specified using either absolute or relative URLs (e.g., <code>index.html</code>).</p> - -<p>The "v1" comment in the example above is there for a good reason. Browsers only update an application cache when the manifest file changes, byte for byte. If you change a cached resource (for example, you update the <code>header.png</code> image with new content), you must also change the content of the manifest file in order to let browsers know that they need to refresh the cache. You can make any change you want to the manifest file, but revising a version number is the recommended best practice.</p> - -<div class="warning"><strong>Important:</strong> Do not specify the manifest itself in the cache manifest file, otherwise it will be nearly impossible to inform the browser a new manifest is available.</div> - -<h3 id="Sections_in_a_cache_manifest_file_CACHE_NETWORK_and_FALLBACK">Sections in a cache manifest file: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code></h3> - -<p>A manifest can have three distinct sections: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>.</p> - -<dl> - <dt><code>CACHE:</code></dt> - <dd>This is the default section for entries in a cache manifest file. Files listed under the <code>CACHE:</code> section header (or immediately after the <code>CACHE MANIFEST</code> line) are explicitly cached after they're downloaded for the first time.</dd> - <dt><code>NETWORK:</code></dt> - <dd>Files listed under the <code>NETWORK:</code> 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 <code>*</code> can be used once. Most sites need <code>*</code>.</dd> - <dt><code>FALLBACK:</code></dt> - <dd>The <code>FALLBACK:</code> section specifies fallback pages the browser should use if a resource is inaccessible. Each entry in this section lists two URIs—the first is the resource, the second is the fallback. Both URIs must be relative and from the same origin as the manifest file. Wildcards may be used.</dd> -</dl> - -<p>The <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK </code>sections can be listed in any order in a cache manifest file, and each section can appear more than once in a single manifest.</p> - -<h3 id="Example_2_a_more_complete_cache_manifest_file">Example 2: a more complete cache manifest file</h3> - -<p>The following is a more complete cache manifest file for the imaginary web site at <span class="nowiki">www.example.com</span>:</p> - -<pre class="eval">CACHE MANIFEST -# v1 2011-08-14 -# This is another comment -index.html -cache.html -style.css -image1.png - -# Use from network if available -NETWORK: -network.html - -# Fallback content -FALLBACK: -. fallback.html -</pre> - -<p>This example uses <code>NETWORK</code> and <code>FALLBACK</code> sections to specify that the <code>network.html</code> page must always be retrieved from the network, and that the <code>fallback.html</code> page should be served as a fallback resource (e.g., in case a connection to the server cannot be established).</p> - -<h3 id="Structure_of_a_cache_manifest_file">Structure of a cache manifest file</h3> - -<p>Cache manifest files must be served with the <code>text/cache-manifest</code> MIME type. All resources served using this MIME type must follow the syntax for an application cache manifest, as defined in this section.</p> - -<p>Cache manifests are UTF-8 format text files, and may optionally include a BOM character. Newlines may be represented by line feed (<code>U+000A</code>), carriage return (<code>U+000D</code>), or carriage return and line feed both.</p> - -<p>The first line of the cache manifest must consist of the string <code>CACHE MANIFEST</code> (with a single <code>U+0020</code> space between the two words), followed by zero or more space or tab characters. Any other text on the line is ignored.</p> - -<p>The remainder of the cache manifest must be comprised of zero or more of the following lines:</p> - -<dl> - <dt>Blank line</dt> - <dd>You may use blank lines comprised of zero or more space and tab characters.</dd> - <dt>Comment</dt> - <dd>Comments consist of zero or more tabs or spaces followed by a single <code>#</code> character, followed by zero or more characters of comment text. Comments may only be used on their own lines (after the initial <code>CACHE MANIFEST</code> line), and cannot be appended to other lines. This means that you cannot specify fragment identifiers.</dd> - <dt>Section header</dt> - <dd>Section headers specify which section of the cache manifest is being manipulated. There are three possible section headers:</dd> -</dl> - -<blockquote> -<table class="standard-table"> - <tbody> - <tr> - <th>Section header</th> - <th>Description</th> - </tr> - <tr> - <td><code>CACHE:</code></td> - <td>Switches to the explicit section of the cache manifest (this is the default section).</td> - </tr> - <tr> - <td><code>NETWORK:</code></td> - <td>Switches to the online whitelist section of the cache manifest.</td> - </tr> - <tr> - <td><code>FALLBACK:</code></td> - <td>Switches to the fallback section of the cache manifest.</td> - </tr> - </tbody> -</table> -</blockquote> - -<dl> - <dd>The section header line may include whitespaces, but must include the colon (<code>:</code>) in the section name.</dd> - <dt>Section data</dt> - <dd>The format for lines of data varies from section to section. In the explicit (<code>CACHE:</code>) section, each line is a valid URI or IRI reference to a resource to cache (no wildcard characters are allowed in this sections). Whitespace is allowed before and after the URI or IRI on each line. In the Fallback section each line is a valid URI or IRI reference to a resource, followed by a fallback resource that is to be served up when a connection with the server cannot be made. In the network section, each line is a valid URI or IRI reference to a resource to fetch from the network (or the wildcard character <code>*</code> can be used in this section). - <div class="note"><strong>Note: </strong>Relative URIs are relative to the cache manifest's URI, not to the URI of the document referencing the manifest.</div> - </dd> -</dl> - -<p>Cache manifest files can switch from section to section at will (each section header can be used more than once), and sections are allowed to be empty.</p> - -<h2 id="Resources_in_an_application_cache">Resources in an application cache</h2> - -<p>An application cache always includes at least one resource, identified by URI. All resources fit into one of the following categories:</p> - -<dl> - <dt>Master entries</dt> - <dd>These are resources added to the cache because a browsing context visited by the user included a document that indicated that it was in this cache using its <code>manifest</code> attribute.</dd> - <dt>Explicit entries</dt> - <dd>These are resources explicitly listed in the application's cache manifest file.</dd> - <dt>Network entries</dt> - <dd>These are resources listed in the application's cache manifest files as network entries.</dd> - <dt>Fallback entries</dt> - <dd>These are resources listed in the application's cache manifest files as fallback entries.</dd> -</dl> - -<div class="note"><strong>Note:</strong> 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.</div> - -<p>Resource categories are described in greater detail below.</p> - -<h3 id="Master_entries">Master entries</h3> - -<p>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 <a href="http://www.example.com/entry.html">http://www.example.com/entry.html</a>, which looks like this:</p> - -<pre class="brush: html"><html manifest="example.appcache"> - <h1>Application Cache Example</h1> -</html> -</pre> - -<p>If <code>entry.html</code> is not listed in the <code>example.appcache</code> cache manifest file, visiting the <code>entry.html</code> page causes <code>entry.html</code> to be added to the application cache as a master entry.</p> - -<h3 id="Explicit_entries">Explicit entries</h3> - -<p>Explicit entries are resources that are explicitly listed in the <code>CACHE </code>section of a cache manifest file.</p> - -<h3 id="Network_entries">Network entries</h3> - -<p>The <code>NETWORK</code> 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 <code>NETWORK</code> section are loaded from the server instead of the cache. This lets the browser's security model protect the user from potential security breaches by limiting access to approved resources.</p> - -<p>As an example, you can use network entries to load and execute scripts and other code from the server instead of the cache:</p> - -<pre class="eval">CACHE MANIFEST -NETWORK: -/api -</pre> - -<p>The cache manifest section listed above ensures that requests to load resources contained in the <code><a href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> subtree always go to the network without attempting to access the cache.</p> - -<div class="note"><strong>Note</strong>: Simply omitting master entries (files that have the <code>manifest</code> attribute set in the <code>html</code> element) from the manifest file would not have the same result, because master entries will be added—and subsequently served from—the application cache.</div> - -<h3 id="Fallback_entries">Fallback entries</h3> - -<p>Fallback entries are used when an attempt to load a resource fails. For example, let's say the cache manifest file <code><a href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> includes the following content:</p> - -<pre class="eval">CACHE MANIFEST -FALLBACK: -example/bar/ example.html -</pre> - -<p>Any request to <code><a href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code> 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 <code>example.html</code> instead.</p> - -<h2 id="Cache_states">Cache states</h2> - -<p>Each application cache has a <strong>state</strong>, 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:</p> - -<dl> - <dt><code>UNCACHED</code></dt> - <dd>A special value that indicates that an application cache object is not fully initialized.</dd> - <dt><code>IDLE</code></dt> - <dd>The application cache is not currently in the process of being updated.</dd> - <dt><code>CHECKING</code></dt> - <dd>The manifest is being fetched and checked for updates.</dd> - <dt><code>DOWNLOADING</code></dt> - <dd>Resources are being downloaded to be added to the cache, due to a changed resource manifest.</dd> - <dt><code>UPDATEREADY</code></dt> - <dd>There is a new version of the application cache available. There is a corresponding <code>updateready</code> event, which is fired instead of the <code>cached</code> event when a new update has been downloaded but not yet activated using the <code>swapCache()</code> method.</dd> - <dt><code>OBSOLETE</code></dt> - <dd>The application cache group is now obsolete.</dd> -</dl> - -<h2 id="Testing_for_updates_to_the_cache_manifest">Testing for updates to the cache manifest</h2> - -<p>You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test <code>window.applicationCache.status</code>.</p> - -<pre class="brush: js">function onUpdateReady() { - console.log('found new version!'); -} -window.applicationCache.addEventListener('updateready', onUpdateReady); -if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { - onUpdateReady(); -}</pre> - -<p>To manually start testing for a new manifest file, you can use <code>window.applicationCache.update()</code>.</p> - -<h2 id="Gotchas">Gotchas</h2> - -<ul> - <li>Never access cached files by using traditional GET parameters (like <code>other-cached-page.html?parameterName=value</code>). This will make the browser bypass the cache and attempt to get it from network. To link to cached resources that have parameters parsed in JavaScript use parameters in the hash part of the link, such as <code>other-cached-page.html#whatever?parameterName=value</code>.</li> - <li>When applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. You must update the cache manifest file itself before the browser retrieves and uses the updated files. You can do this programmatically using <code>window.applicationCache.swapCache()</code>, though resources that have already been loaded will not be affected. To make sure that resources are loaded from a new version of the application cache, refreshing the page is ideal.</li> - <li>It's a good idea to set expires headers on your web server for <code>*.appcache</code> files to expire immediately. This avoids the risk of caching manifest files. For example, in Apache you can specify such a configuration as follows:<br> - <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> -</ul> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Edge</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>4.0</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop("1.9.1")}}<sup>[1]</sup></td> - <td>10.0</td> - <td>10.6</td> - <td>4.0</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Edge</th> - <th>Firefox Mobile (Gecko)</th> - <th>Firefox OS</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>2.1</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>1.0.1<sup>[2]</sup></td> - <td>11.0<sup>[3]</sup></td> - <td>11.0</td> - <td>3.2</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Versions of Firefox prior to 3.5 ignore the <code>NETWORK</code> and <code>FALLBACK</code> sections of the cache manifest file.</p> - -<p>[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 <a href="/en-US/Apps/Build/Manifest#appcache_path">appcache_path field</a>.</p> - -<p>[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.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> - <li><a href="http://appcache.offline.technology/">Appcache Facts</a> - detailed information on AppCache idiosyncrasies</li> - <li><a href="http://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Application Cache is a Douchebag</a> - <ul> - <li><a href="http://flailingmonkey.com/application-cache-not-a-douchebag">The Application Cache is no longer a Douchebag</a> - an overview of the app cache debugging tools added in Firefox 23.</li> - </ul> - </li> - <li><a href="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li> - <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> - <li><a href="http://www.w3.org/TR/offline-webapps/">W3C Working Group Note: Offline Web Applications</a></li> - <li><a href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> - <li><a href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a> (IBM developerWorks)</li> - <li><a href="/en-US/docs/Application_cache_implementation_overview">Application cache implementation overview</a></li> - <li><a href="//www.onlinewebcheck.com/check.php?adv=1">OnlineWebCheck.com - Check cache manifest file syntax</a> (Desktop app for Windows)</li> -</ul> |