--- title: Cache.add() slug: Web/API/Cache/add translation_of: Web/API/Cache/add --- <p>{{APIRef("Service Workers API")}}{{SeeCompatTable}}</p> <p>{{domxref("Cache")}}接口的 <strong><code>add()</code></strong>方法接受一个URL作为参数,请求参数指定的URL,并将返回的response对象添加到给定的cache中。 <code>add()</code> 方法在功能上等同于以下代码:</p> <pre class="brush: js">fetch(url).then(function (response) { if (!response.ok) { throw new TypeError('bad response status'); } return cache.put(url, response); })</pre> <p>对于更复杂的操作,您可以直接使用{{domxref("Cache.put","Cache.put()")}}这个API。</p> <div class="note"> <p><span style="font-size: 14px;"><strong>注意</strong></span>: <code>add()</code> 将会覆盖之前存储在cache中与request匹配的任何key/value对。</p> </div> <div class="note"> <p><span style="font-size: 14px;"><strong>注意</strong></span>: 之前的Cache (Blink 和 Gecko内核版本) 在实现{{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, 和 {{domxref("Cache.put")}} 的策略是在response结果完全写入缓存后才会resolve当前的promise。更新后的规范版本中一旦条目被记录到数据库就会resolve当前的promise,即使当前response结果还在传输中。</p> </div> <h2 id="语法">语法</h2> <pre class="sytaxbox"><em>cache</em>.add(<em>request</em>).then(function() { //request has been added to the cache }); </pre> <h3 id="参数">参数</h3> <dl> <dt>request</dt> <dd>要添加到cache的request。它可以是一个 {{domxref("Request")}} 对象,也可以是 URL。</dd> </dl> <h3 id="返回值">返回值</h3> <p>void返回值的 {{jsxref("Promise")}} </p> <h3 id="Exceptions">Exceptions</h3> <table class="standard-table"> <thead> <tr> <th scope="col"><strong>Exception</strong></th> <th scope="col"><strong>Happens when</strong></th> </tr> </thead> <tbody> <tr> <td><code>TypeError</code></td> <td> <p>URL的协议不是 <code>http</code> 或 <code>https。</code></p> <p>请求返回的http状态码不是2xx (不是一个成功的响应) 。这种情况常常发生在请求不成功,或者是一个没有配置CORS的跨域请求(这种情况下返回的状态码永远是0)。</p> </td> </tr> </tbody> </table> <h2 id="示例">示例</h2> <p>下面的代码块等待 {{domxref("InstallEvent")}} 事件触发,然后运行 {{domxref("ExtendableEvent.waitUntil","waitUntil")}} 来处理该应用程序的安装过程。 包括调用 {{domxref("CacheStorage.open")}} 来创建一个新的缓存,然后使用 {{domxref("Cache.add")}} 来添加一个请求资源到该缓存。</p> <pre class="brush: js">this.addEventListener('install', function(event) { event.waitUntil( caches.open('v1').then(function(cache) { return cache.add('/sw-test/index.html'); }) ); }); </pre> <h2 id="规范">规范</h2> <table class="standard-table"> <tbody> <tr> <th scope="col">Specification</th> <th scope="col">Status</th> <th scope="col">Comment</th> </tr> <tr> <td>{{SpecName('Service Workers', '#cache', 'Cache')}}</td> <td>{{Spec2('Service Workers')}}</td> <td>Initial definition.</td> </tr> </tbody> </table> <h2 id="浏览器兼容性">浏览器兼容性</h2> {{Compat("api.Cache.add")}} <h2 id="参见">参见</h2> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> <li>{{domxref("Cache")}}</li> <li>{{domxref("WorkerGlobalScope.caches")}}</li> </ul>