UNPKG

2.73 kBMarkdownView Raw
1---
2layout: doc_page
3title: Getting started
4description: Make your app offline first in about 30 minutes
5order: 1
6sections:
7 - anchor: installation
8 title: Installation
9 - anchor: offline-first
10 title: Offline first
11---
12
13
14### Installation
15
16To get started with Ember Service Worker, install the addon in your exisiting
17Ember.js project:
18
19{% highlight shell %}
20ember install ember-service-worker
21{% endhighlight %}
22
23If you now rebuild and visit your Ember app it should install a Service Worker
24when the page loads.
25
26### Offline first
27
28Let's now add some plugins to make the app offline first. This is done by
29installing some aditional addons:
30
31{% highlight shell %}
32ember install ember-service-worker-index
33ember install ember-service-worker-asset-cache
34{% endhighlight %}
35
36These plugins will take care of caching your `index.html` page and static
37assets. If you again restart rebuild and visit your Ember app, it caches
38your `index.html` file and static assets. If you now disconnect your internet
39connection (or turn on 'offline' mode in your browser's dev tools) and refresh
40the page, your app should still load!
41
42There might be a small gotcha though, that is it doesn't cache any non-static
43resources, like requests to an API. To do this, we need to install another
44plugin:
45
46{% highlight shell %}
47ember install ember-service-worker-cache-fallback
48{% endhighlight %}
49
50This plugin will cache any request that you configure it to do so, but will only
51serve the contents from the cache when the resource won't load.
52To configure which resources it should cache we need to add some configuration to
53the `ember-cli-build.js` file that should be in the root of your Ember.js
54project. The configuration depends on what kind of resources your app loads.
55Here's an example configuration:
56
57{% highlight javascript %}
58var EmberApp = require('ember-cli/lib/broccoli/ember-app');
59
60module.exports = function(defaults) {
61 var app = new EmberApp(defaults, {
62 'esw-cache-fallback': {
63 patterns: [
64 '/api/v1/(.+)'
65 ],
66 }
67 });
68
69 return app.toTree();
70};
71{% endhighlight %}
72
73The `patterns` property in the `esw-cache-fallback` configuration should be an
74array of regular expressions that describe the URLs it can cache. In the example
75it's configured to cache anything resource of which the URL starts with `/api/v1/`.
76
77Update the configuration to your liking and then rebuild and visit your app
78again. Now browse around your app for a few moments while online to prime the
79fallback cache, afterwards put your browser into offline mode and try to load a
80page you have visited before. If everything went well, it should now also serve
81your API responses from the cache.
82
83Congratulations! Your app is now offline first.