在 Rails 资产管道中使用 Service Worker
Turn your Rails app into a Progressive Web App. Use Service Worker with the Rails asset pipeline
The Rails asset pipeline makes a number of assumptions about what's best for deploying JavaScript, including asset digest fingerprints and long-lived cache headers - mostly to increase "cacheability". Rails also assumes a single parent directory, /public/assets, to make it easier to look up the file path for a given asset.
Service worker assets must play by different rules. Consider these behaviors:
Service workers may only be active from within the scope from which they are
served. So if you try to register a service worker from a Rails asset pipeline
path, like /assets/serviceworker-abcd1234.js, it will only be able to interact
with requests and responses within /assets/**. This is not what we want.
MDN states browsers check for updated service worker scripts in the background every 24 hours (possibly less). Rails developers wouldn't be able to take advantage of this feature since the fingerprint strategy means assets at a given url are immutable. Beside fingerprintings, the Cache-Control headers used for static files served from Rails also work against browser's treatment of service workers.
We want Sprockets to compile service worker JavaScript from ES6/7, CoffeeScript, ERB, etc. but must remove the caching and scoping mechanisms offered by Rails defaults. This is where serviceworker-rails comes in.
Check out the blog post for more background.
See various examples of using Service Workers in the demo Rails app, Service Worker Rails Sandbox. The source code is also on GitHub.
Add this line to your application's Gemfile:
gem 'serviceworker-rails'And then execute:
$ bundleOr install it yourself as:
$ gem install serviceworker-railsTo set up your Rails project for use with a Service Worker, you either use the Rails generator and edit the generated files as needed, or you can follow the manual installation steps.
After bundling the gem in your Rails project, run the generator from the root of your Rails project.
$ rails g serviceworker:installThe generator will create the following files:
config/initializers/serviceworker.rb - for configuring your Rails appapp/assets/javascripts/serviceworker.js.erb - a blank Service Worker
script with some example strategiesapp/assets/javascripts/serviceworker-companion.js - a snippet of JavaScript
necessary to register your Service Worker in the browserapp/assets/javascripts/manifest.json.erb - a starter web app manifest
pointing to some default app icons provided by the gempublic/offline.html - a starter offline pageIt will also make the following modifications to existing files:
serviceworker.js and manifest.json to the list of compiled assets in
config/initializers/assets.rbhead of app/views/layouts/application.html.erb for
linking to the web app manifestDue to the variety of possible javascript implementations, you will still need to perform the following task manually:
//= require serviceworker-companion in app/assets/javascripts/application.js. If you're using Importmaps and the app/javascript directory, you can move the generated files in app/assets/javascripts to app/javascript and add import 'serviceworker-companion' to app/javascript/application.js.NOTE Given that Service Worker operates in a separate browser thread, outside the context of your web pages, you don't want to include serviceworker.js script in your application.js. So if you have a line like require_tree . in your application.js file, you'll either need to move your serviceworker.js to another location or replace require_tree with something more explicit.
To learn more about each of the changes or to perform the set up yourself, check out the manual setup section below.
Let's add a ServiceWorker to cache some of your JavaScript and CSS assets. We'll assume you already have a Rails application using the asset pipeline built on Sprockets.
Create a JavaScript file called app/assets/javascripts/serviceworker.js.erb:
…For use in production, instruct Sprockets to precompile service worker scripts separately from application.js, as in the following example:
You'll need to register the service worker with a companion script in your main page JavaScript, like application.js. You can use the following:
// app/assets/javascripts/serviceworker-companion.js
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/serviceworker.js', { scope: './' })
.then(function(reg) {
console.log('[Page] Service worker registered!');
});
}
// app/assets/javascripts/application.js
// ...
//= require serviceworker-companionYou may also want to create a manifest.json file to make your web app installable.
// app/assets/javascripts/manifest.json
{
"name": "My Progressive Rails App",
"short_name": "Progressive",
"start_url": "/"
}You'd then link to your manifest from the application layout:
Next, add a new initializer as show below to instruct the serviceworker-rails
middleware how to route requests for assets by canonical url.
# config/initializers/serviceworker.rb
Rails.application.configure do
config.serviceworker.routes.draw do
match "/serviceworker.js"
match "/manifest.json"
end
end# config/initializers/assets.rb
Rails.application.configure do
config.assets.precompile += %w[serviceworker.js manifest.json]
endAt this point, restart your Rails app and reload a page in your app in Chrome or Firefox. Using dev tools, you should be able to determine.
/serviceworker.jsapp/assets/javascripts/serviceworker.js.erb.So far so good? At this point, all we've done is pre-fetched assets and added them to the cache, but we're not doing anything with them yet.
Now, we can use the service worker to intercept requests and either serve them from the cache if they exist there or fallback to the network response otherwise. In most cases, we can expect responses coming from the local cache to be much faster than those coming from the network.
…When serviceworker-rails is required in your Gemfile, it will insert a middleware into the Rails
middleware stack. You'll want to configure it by mapping serviceworker routes to
Sprockets JavaScript assets in an initializer, like the example below.
…Serviceworker::Rails will insert a Cache-Control header to instruct browsers
not to cache your serviceworkers by default. You can customize the headers for all service worker routes if you'd like,
such as adding the experimental Service-Worker-Allowed header to set the allowed scope.
config.serviceworker.headers["Service-Worker-Allowed"] = "/"
config.serviceworker.headers["X-Custom-Header"] = "foobar"After checking out the repo, run bin/setup to install dependencies. Then, run bin/rake to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
Bug reports and pull requests are welcome on GitHub at https://github.com/rossta/serviceworker-rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
The gem is available as open source under the terms of the MIT License.
暂无开放 Issues,或尚未同步最近议题。