diff options
| author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
|---|---|---|
| committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
| commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
| tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/ru/web/api/extendableevent | |
| parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
| download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip | |
initial commit
Diffstat (limited to 'files/ru/web/api/extendableevent')
| -rw-r--r-- | files/ru/web/api/extendableevent/index.html | 130 | ||||
| -rw-r--r-- | files/ru/web/api/extendableevent/waituntil/index.html | 77 |
2 files changed, 207 insertions, 0 deletions
diff --git a/files/ru/web/api/extendableevent/index.html b/files/ru/web/api/extendableevent/index.html new file mode 100644 index 0000000000..336ae70a26 --- /dev/null +++ b/files/ru/web/api/extendableevent/index.html @@ -0,0 +1,130 @@ +--- +title: ExtendableEvent +slug: Web/API/ExtendableEvent +tags: + - API + - Experimental + - ExtendableEvent + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - ServiceWorker + - TopicStub + - Workers +translation_of: Web/API/ExtendableEvent +--- +<div>{{APIRef("Service Workers API")}}</div> + +<p>The <strong><code>ExtendableEvent</code></strong> interface extends the lifetime of the <code><a href="/en-US/docs/Web/API/ServiceWorkerGlobalScope/install">install</a></code> and <code><a href="/en-US/docs/Web/API/ServiceWorkerGlobalScope/activate">activate</a></code> events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like {{domxref("FetchEvent")}}) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.</p> + +<p>If {{domxref("ExtendableEvent.waitUntil","waitUntil()")}} is called outside of the <code>ExtendableEvent</code> handler, the browser should throw an <code>InvalidStateError</code>; note also that multiple calls will stack up, and the resulting promises will be added to the list of <a href="https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises">extend lifetime promises</a>.</p> + +<div class="note"> +<p><strong>Note</strong>: The behaviour described in the above paragraph was fixed in Firefox 43 (see {{bug(1180274)}}.)</p> +</div> + +<p>This interface inherits from the {{domxref("Event")}} interface.</p> + +<p>{{InheritanceDiagram(700, 60, 20)}}</p> + +<div class="note"> +<p><strong>Note</strong>: This interface is only available when the global scope is a {{domxref("ServiceWorkerGlobalScope")}}. It is not available when it is a {{domxref("Window")}}, or the scope of another kind of worker.</p> +</div> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("ExtendableEvent.ExtendableEvent()", "ExtendableEvent()")}}</dt> + <dd>Creates a new <code>ExtendableEvent</code> object.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<p><em>Doesn't implement any specific properties, but inherits properties from its parent, {{domxref("Event")}}.</em></p> + +<h2 id="Methods">Methods</h2> + +<p><em>Inherits methods from its parent, </em><em>{{domxref("Event")}}</em>.</p> + +<dl> + <dt>{{domxref("ExtendableEvent.waitUntil", "ExtendableEvent.waitUntil()")}}</dt> + <dd> + <p>Extends the lifetime of the event. It is intended to be called in the <code><a href="/en-US/docs/Web/API/ServiceWorkerGlobalScope/install">install</a></code> {{domxref("EventHandler")}} for the {{domxref("ServiceWorkerRegistration.installing", "installing")}} worker and on the <code><a href="/en-US/docs/Web/API/ServiceWorkerGlobalScope/activate">activate</a></code> {{domxref("EventHandler")}} for the {{domxref("ServiceWorkerRegistration.active", "active")}} worker.</p> + </dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>This code snippet is from the <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/prefetch/service-worker.js">service worker prefetch sample</a> (see <a href="https://googlechrome.github.io/samples/service-worker/prefetch/">prefetch example live</a>.) The code calls {{domxref("ExtendableEvent.waitUntil()")}} in {{domxref("ServiceWorkerGlobalScope.oninstall")}}, delaying treating the {{domxref("ServiceWorkerRegistration.installing")}} worker as installed until the passed promise resolves successfully. The promise resolves when all resources have been fetched and cached, or else when any exception occurs.</p> + +<p>The code snippet also shows a best practice for versioning caches used by the service worker. Though there's only one cache in this example, the same approach can be used for multiple caches. It maps a shorthand identifier for a cache to a specific, versioned cache name.</p> + +<div class="note"> +<p><strong>Note</strong>: In Chrome, logging statements are visible via the "Inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals.</p> +</div> + +<pre class="brush: js notranslate">var CACHE_VERSION = 1; +var CURRENT_CACHES = { + prefetch: 'prefetch-cache-v' + CACHE_VERSION +}; + +self.addEventListener('install', function(event) { + var urlsToPrefetch = [ + './static/pre_fetched.txt', + './static/pre_fetched.html', + 'https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif' + ]; + + console.log('Handling install event. Resources to pre-fetch:', urlsToPrefetch); + + event.waitUntil( + caches.open(CURRENT_CACHES['prefetch']).then(function(cache) { + return cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) { + return new Request(urlToPrefetch, {mode: 'no-cors'}); + })).then(function() { + console.log('All resources have been fetched and cached.'); + }); + }).catch(function(error) { + console.error('Pre-fetching failed:', error); + }) + ); +});</pre> + +<div class="note"><strong>Important</strong>: When fetching resources, it's very important to use <code>{mode: 'no-cors'}</code> if there is any chance that the resources are served off of a server that doesn't support {{glossary("CORS")}}. In this example, <a href="http://www.chromium.org">www.chromium.org</a> doesn't support CORS.</div> + +<h2 id="Specifications">Specifications</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', '#extendableevent', 'ExtendableEvent')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("api.ExtendableEvent")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Using Service Workers</a></li> + <li><a class="external external-icon" href="https://github.com/mdn/sw-test">Service workers basic code example</a></li> + <li><a class="external external-icon" href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li>{{jsxref("Promise")}}</li> + <li><a href="/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Using web workers</a></li> +</ul> diff --git a/files/ru/web/api/extendableevent/waituntil/index.html b/files/ru/web/api/extendableevent/waituntil/index.html new file mode 100644 index 0000000000..136770f499 --- /dev/null +++ b/files/ru/web/api/extendableevent/waituntil/index.html @@ -0,0 +1,77 @@ +--- +title: ExtendableEvent.waitUntil() +slug: Web/API/ExtendableEvent/waitUntil +translation_of: Web/API/ExtendableEvent/waitUntil +--- +<p>{{APIRef("Service Workers API")}}</p> + +<p><span class="seoSummary">Метод <code><strong>ExtendableEvent.waitUntil()</strong></code> сообщает диспетчеру событий, что выполняется действие. Также этот метод может быть использован, для того чтобы определить было ли то действие успешным. В рамках service workers, <code>waitUntil()</code> сообщает браузеру, что действие продолжается пока обещание не завершится (<em>promise settles</em>) и браузер не должен прерывать service worker если он хочет, чтобы это действие завершилось.</span></p> + +<p>События <code>install</code> в {{domxref("ServiceWorkerGlobalScope", "service workers")}} используют <code>waitUntil()</code> чтобы задержать service worker в {{domxref("ServiceWorkerRegistration.installing", "installing")}} фазе пока не завершатся задачи. Если обещание переданное в <code>waitUntil()</code> отклоняется, установка считается неудачной и устанавлеваемый service worker отбрасывается. В первую очередь это используется для гарантии того, что service worker не рассматривается как установленный (installed), пока все основные кэши на которые он зависит успешно не заполнены.</p> + +<p>События <code>activate</code> в {{domxref("ServiceWorkerGlobalScope", "service workers")}} используют <code>waitUntil()</code> для размещения в буфере функциональных событий таких как <code>fetch</code> и <code>push</code> пока обещание переданное в <code>waitUntil()</code> не завершится успешно. Это дает service worker время, чтобы обновить схемы базы данных и удалить устаревшие {{domxref("Cache", "caches")}}, таким образом другие события могут полагаться на полностью обновленное состояние.</p> + +<p>Метод <code>waitUntil()</code> должен быть изначально вызван внутри события обратного вызова (<em>event callback</em>), но после этого он может быть вызван множество раз, до тех пор пока все обещания переданные в него не завершатся успешно.</p> + +<div class="note"> +<p><strong>Примечание</strong>: Поведение описанное в параграфе выше, было исправлено в Firefix 43 (смотрите {{bug(1180274)}}).</p> +</div> + +<h2 id="Синтаксис">Синтаксис</h2> + +<pre class="syntaxbox notranslate"><em>extendableEvent</em>.waitUntil(<em>promise</em>);</pre> + +<h3 id="Параметры">Параметры</h3> + +<p>{{jsxref("Promise")}}.</p> + +<h3 id="Возвращаемое_значение">Возвращаемое значение</h3> + +<p><code>undefined</code>.</p> + +<h2 id="Примеры">Примеры</h2> + +<p>Использование <code>waitUntil()</code> внутри события <code>install</code> в service worker:</p> + +<pre class="brush: js;highlight:[10] notranslate">addEventListener('install', event => { + const preCache = async () => { + const cache = await caches.open('static-v1'); + return cache.addAll([ + '/', + '/about/', + '/static/styles.css' + ]); + }; + event.waitUntil(preCache()); +});</pre> + +<h2 id="Спецификации">Спецификации</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Спецификации</th> + <th scope="col">Статус</th> + <th scope="col">Комментарий</th> + </tr> + <tr> + <td>{{SpecName('Service Workers', '#dom-extendableevent-waituntil', 'waitUntil()')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Изначальное определение</td> + </tr> + </tbody> +</table> + +<h2 id="Совместимость_с_браузерами">Совместимость с браузерами</h2> + +<div class="hidden">Таблица совместимости на этой странице сгенерирована из структурированных данных. Если вы хотите внести свой вклад в данные, пожалуйста посмотрите на <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> и отправьте нам pull request.</div> + +<p>{{Compat("api.ExtendableEvent.waitUntil")}}</p> + +<h2 id="Смотрите_также">Смотрите также</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Использование Service Workers</a></li> + <li><a class="external external-icon" href="https://jakearchibald.github.io/isserviceworkerready/">Готов ли ServiceWorker?</a></li> + <li>{{jsxref("Promise")}}</li> +</ul> |
