diff options
Diffstat (limited to 'files/th/web/api/cachestorage/index.html')
-rw-r--r-- | files/th/web/api/cachestorage/index.html | 189 |
1 files changed, 189 insertions, 0 deletions
diff --git a/files/th/web/api/cachestorage/index.html b/files/th/web/api/cachestorage/index.html new file mode 100644 index 0000000000..1debf49bb0 --- /dev/null +++ b/files/th/web/api/cachestorage/index.html @@ -0,0 +1,189 @@ +--- +title: CacheStorage +slug: Web/API/CacheStorage +translation_of: Web/API/CacheStorage +--- +<p><font><font>{{APIRef ("Service Workers API")}}</font></font></p> + +<p><strong><code>CacheStorage</code></strong><font><font>อินเตอร์เฟซที่แสดงให้เห็นถึงการจัดเก็บข้อมูลสำหรับ {{domxref ( "แคช")}} วัตถุ</font></font></p> + +<p><font><font>อินเทอร์เฟซ:</font></font></p> + +<ul> + <li><font><font>จัดเตรียมไดเร็กทอรีหลักของแคชที่มีชื่อทั้งหมดซึ่งสามารถเข้าถึงได้โดย {{domxref ("ServiceWorker")}} หรือผู้ปฏิบัติงานประเภทอื่นหรือขอบเขต {{domxref ("window")}} (คุณไม่ จำกัด เฉพาะ โดยใช้กับพนักงานบริการแม้ว่าข้อมูลจำเพาะ {{SpecName ('Service Workers')}} จะกำหนดก็ตาม)</font></font> + + <div class="note"><strong><font><font>หมายเหตุ</font></font></strong><font><font> : </font></font><a href="https://bugs.chromium.org/p/chromium/issues/detail?id=1026063"><font><font>Chrome และ Safari 7เพียงเปิดเผย `CacheStorage` กับบริบทหน้าต่างผ่าน </font></font></a><font><font>HTTPS </font><font>{{domxref ("window.caches")}} จะไม่ถูกกำหนดเว้นแต่จะมีการกำหนดค่าใบรับรอง SSL</font></font></div> + </li> + <li><font><font>รักษาการแมปชื่อสตริงกับออบเจ็กต์ {{domxref ("Cache")}} ที่เกี่ยวข้อง</font></font></li> +</ul> + +<p><font><font>ใช้ {{domxref ("CacheStorage.open ()")}} เพื่อรับอินสแตนซ์ {{domxref ("Cache")}}</font></font></p> + +<p>Use {{domxref("CacheStorage.match()")}} to check if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the <code>CacheStorage</code> object tracks.</p> + +<p>You can access <code>CacheStorage</code> through the global {{domxref("WindowOrWorkerGlobalScope.caches", "caches")}} property.</p> + +<div class="note"><strong>Note</strong>: CacheStorage always rejects with a <code>SecurityError</code> on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the future.) When testing, you can get around this by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Devtools options/gear menu.</div> + +<div class="note"><strong>Note</strong>: {{domxref("CacheStorage.match()")}} is a convenience method. Equivalent functionality to match a cache entry can be implemented by returning an array of cache names from {{domxref("CacheStorage.keys()")}}, opening each cache with {{domxref("CacheStorage.open()")}}, and matching the one you want with {{domxref("Cache.match()")}}.</div> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("CacheStorage.match()")}}</dt> + <dd>Checks if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the {{domxref("CacheStorage")}} object tracks, and returns a {{jsxref("Promise")}} that resolves to that match.</dd> + <dt>{{domxref("CacheStorage.has()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that resolves to <code>true</code> if a {{domxref("Cache")}} object matching the <code>cacheName</code> exists.</dd> + <dt>{{domxref("CacheStorage.open()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that resolves to the {{domxref("Cache")}} object matching the <code>cacheName</code> (a new cache is created if it doesn't already exist.)</dd> + <dt>{{domxref("CacheStorage.delete()")}}</dt> + <dd>Finds the {{domxref("Cache")}} object matching the <code>cacheName</code>, and if found, deletes the {{domxref("Cache")}} object and returns a {{jsxref("Promise")}} that resolves to <code>true</code>. If no {{domxref("Cache")}} object is found, it resolves to <code>false</code>.</dd> + <dt>{{domxref("CacheStorage.keys()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that will resolve with an array containing strings corresponding to all of the named {{domxref("Cache")}} objects tracked by the {{domxref("CacheStorage")}}. Use this method to iterate over a list of all the {{domxref("Cache")}} objects.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>This code snippet is from the MDN <a href="https://github.com/mdn/sw-test/">sw-test example</a> (see <a href="https://mdn.github.io/sw-test/">sw-test running live</a>.) This service worker script waits for an {{domxref("InstallEvent")}} to fire, then runs {{domxref("ExtendableEvent.waitUntil","waitUntil")}} to handle the install process for the app. This consists of calling {{domxref("CacheStorage.open")}} to create a new cache, then using {{domxref("Cache.addAll")}} to add a series of assets to it.</p> + +<p>In the second code block, we wait for a {{domxref("FetchEvent")}} to fire. We construct a custom response like so:</p> + +<ol> + <li>Check whether a match for the request is found in the CacheStorage. If so, serve that.</li> + <li>If not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using {{domxref("Cache.put")}} (<code>cache.put(event.request, response.clone())</code>.)</li> + <li>If this fails (e.g. because the network is down), return a fallback response.</li> +</ol> + +<p>Finally, return whatever the custom response ended up being equal to, using {{domxref("FetchEvent.respondWith")}}.</p> + +<pre class="brush: js notranslate">self.addEventListener('install', function(event) { + event.waitUntil( + caches.open('v1').then(function(cache) { + return cache.addAll([ + '/sw-test/', + '/sw-test/index.html', + '/sw-test/style.css', + '/sw-test/app.js', + '/sw-test/image-list.js', + '/sw-test/star-wars-logo.jpg', + '/sw-test/gallery/bountyHunters.jpg', + '/sw-test/gallery/myLittleVader.jpg', + '/sw-test/gallery/snowTroopers.jpg' + ]); + }) + ); +}); + +self.addEventListener('fetch', function(event) { + event.respondWith(caches.match(event.request).then(function(response) { + // caches.match() always resolves + // but in case of success response will have value + if (response !== undefined) { + return response; + } else { + return fetch(event.request).then(function (response) { + // response may be used only once + // we need to save clone to put one copy in cache + // and serve second one + let responseClone = response.clone(); + + caches.open('v1').then(function (cache) { + cache.put(event.request, responseClone); + }); + return response; + }).catch(function () { + return caches.match('/sw-test/gallery/myLittleVader.jpg'); + }); + } + })); +}); +</pre> + +<p>This snippet shows how the API can be used outside of a service worker context, and uses the <code>await</code> operator for much more readable code.</p> + +<pre class="brush: js notranslate">// Try to get data from the cache, but fall back to fetching it live. +async function getData() { + const cacheVersion = 1; + const cacheName = `myapp-${ cacheVersion }`; + const url = 'https://jsonplaceholder.typicode.com/todos/1'; + let cachedData = await getCachedData( cacheName, url ); + + if ( cachedData ) { + console.log( 'Retrieved cached data' ); + return cachedData; + } + + console.log( 'Fetching fresh data' ); + + const cacheStorage = await caches.open( cacheName ); + await cacheStorage.add( url ); + cachedData = await getCachedData( cacheName, url ); + await deleteOldCaches( cacheName ); + + return cachedData; +} + +// Get data from the cache. +async function getCachedData( cacheName, url ) { + const cacheStorage = await caches.open( cacheName ); + const cachedResponse = await cacheStorage.match( url ); + + if ( ! cachedResponse || ! cachedResponse.ok ) { + return false; + } + + return await cachedResponse.json(); +} + +// Delete any old caches to respect user's disk space. +async function deleteOldCaches( currentCache ) { + const keys = await caches.keys(); + + for ( const key of keys ) {<font><font> + const isOurCache = 'myapp-' === key.substr (0, 6);</font></font> +<font><font> + ถ้า (currentCache === คีย์ ||! isOurCache) {</font></font><font><font> + ดำเนินการต่อ;</font></font><font><font> + }</font></font> +<font><font> + caches.delete (คีย์);</font></font><font><font> + }</font></font><font><font> +}</font></font> +<font><font> +ลอง {</font></font><font><font> + const data = รอ getData ();</font></font><font><font> + console.log ({data});</font></font><font><font> +} catch (error) {</font></font><font><font> + console.error ({error});</font></font><font><font> +}</font></font></pre> + +<h2 id="ข้อมูลจำเพาะ"><font><font>ข้อมูลจำเพาะ</font></font></h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col"><font><font>ข้อมูลจำเพาะ</font></font></th> + <th scope="col"><font><font>สถานะ</font></font></th> + <th scope="col"><font><font>แสดงความคิดเห็น</font></font></th> + </tr> + <tr> + <td><font><font>{{SpecName ('Service Workers', '#cachestorage', 'CacheStorage')}}</font></font></td> + <td><font><font>{{Spec2 ('พนักงานบริการ')}}</font></font></td> + <td><font><font>นิยามเริ่มต้น</font></font></td> + </tr> + </tbody> +</table> + +<h2 id="ความเข้ากันได้ของเบราว์เซอร์"><font><font>ความเข้ากันได้ของเบราว์เซอร์</font></font></h2> + +<div class="hidden"><font><font>ตารางความเข้ากันได้ในหน้านี้สร้างขึ้นจากข้อมูลที่มีโครงสร้าง </font><font>หากคุณต้องการมีส่วนร่วมในข้อมูลโปรดดู</font></font><a href="https://github.com/mdn/browser-compat-data"><font><font>https://github.com/mdn/browser-compat-data</font></font></a><font><font>และส่งคำขอดึงข้อมูลมาให้เรา</font></font></div> + +<p><font><font>{{คอมแพต ("api.CacheStorage")}}</font></font></p> + +<h2 id="ดูสิ่งนี้ด้วย"><font><font>ดูสิ่งนี้ด้วย</font></font></h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers"><font><font>การใช้พนักงานบริการ</font></font></a></li> + <li><font><font>{{domxref ("แคช")}}</font></font></li> + <li><font><font>{{domxref ("WindowOrWorkerGlobalScope.caches")}}</font></font></li> +</ul> |