Code Monkey home page Code Monkey logo

sw-precache's Introduction

NPM version Build Status Dependency Status

Generate service worker code that will precache specific resources. See the background doc for more information.

Install

$ npm install --save-dev sw-precache

Usage

Overview

  1. Make sure your site is served using HTTPS! Service worker functionality is only available on pages that are accessed via HTTPS. (http://localhost will also work, to facilitate testing.) The rationale for this restriction is outlined in the "Prefer Secure Origins For Powerful New Features" document.

  2. Incorporate sw-precache into your node-based build script. It should work well with either gulp or Grunt, or other build scripts that run on node. As part of the build process, sw-precache generates fully functional JavaScript code that will take care of precaching and fetching all the resources your site needs to function offline.

  3. Register the service worker JavaScript. The JavaScript that's generated needs to be registered as the controlling service worker for your pages. This technically only needs to be done from within a top-level "entry" page for your site, since the registration includes a scope which will apply to all pages underneath your top-level page. service-worker-registration.js is a sample script that illustrates the best practices for registering the generated service worker code and handling the various lifecycle events.

Example

The project's sample gulpfile.js illustrates its full usage in context. You can run the sample by cloning this repo, using npm install to pull in the dependencies, changing to the demo directory, running gulp serve-dist, and then visiting http://localhost:3000

There is also a basic Gruntfile.js provided as a sample.

Here's a simpler example for a basic use case. It assumes your site's resources are located under app and that you'd like to cache all your JavaScript, HTML, CSS, and image files.

gulp.task('generate-service-worker', function(callback) {
  var fs = require('fs');
  var path = require('path');
  var swPrecache = require('sw-precache');
  var rootDir = 'app';

  swPrecache({
    staticFileGlobs: [rootDir + '/**/*.{js,html,css,png,jpg,gif}'],
    stripPrefix: rootDir
  }, function(error, swFileContents) {
    if (error) {
      return callback(error);
    }
    fs.writeFile(path.join(rootDir, 'service-worker.js'), swFileContents, callback);
  });
});

This task will create app/service-worker.js, which you'll need to register before it can take control of your site's pages. service-worker-registration.js is a ready-to-use script to handle registration.

Considerations

  • Service worker caching should be considered a progressive enhancement. If you follow the model of conditionally registering a service worker only if it's supported (determined by if('serviceWorker' in navigator)), you'll get offline support on browsers with service workers and on browsers that don't support service workers, the offline-specific code will never be called. There's no overhead/breakage for older browsers if you add sw-precache to your build.

  • All resources that are precached will be fetched by a service worker running in a separate thread as soon as the service worker is installed. You should be judicious in what you list in the dynamicUrlToDependencies and staticFileGlobs options, since listing files that are non-essential (large images that are not shown on every page, for instance) will result in browsers downloading more data then is strictly necessary, as soon as they visit your site.

  • Precaching doesn't make sense for all types of resources (see previous point). Other caching strategies, like those outlined in the offline cookbook, can be used in conjunction with sw-precache to provide the best experience for your users. If you do implement additional caching logic, put the code in a separate JavaScript file and include it using the importScripts option.

Options

cacheId [String]

A string used to distinguish the caches created by different web applications that are served off of the same origin and path. While serving completely different sites from the same URL is not likely to be an issue in a production environment, it avoids cache-conflicts when testing various projects all served off of http://localhost. You may want to set it to, e.g., the name property from your package.json.

Default: ''

directoryIndex [String]

Many web servers automatically treat a URL corresponding to a directory (i.e. ending in '/') as if it were a request for a specific index file in that directory, traditionally 'index.html'. sw-precache will take that translation into account and serve the contents a relative directoryIndex file when there's no other match for a URL ending in '/'. To turn off this behavior, set directoryIndex to false or null. To override this behavior for one or more URLs, use the dynamicUrlToDependencies option to explicitly set up mappings between a directory URL and the corresponding file to use.

Default: 'index.html'

dynamicUrlToDependencies [Object⟨String,Array⟨String⟩⟩]

Maps a dynamic URL string to an array of all the files that URL's contents depend on. E.g., if the contents of /pages/home are generated server-side via the templates layout.jade and home.jade, then specify '/pages/home': ['layout.jade', 'home.jade']. The MD5 hash used to determine whether /pages/home has changed will depend on the hashes of both layout.jade and home.jade.

Default: {}

handleFetch [boolean]

Determines whether the fetch event handler is included in the generated service worker code. It is useful to set this to false in development builds, to ensure that features like live reload still work (otherwise, the content would always be served from the service worker cache).

Default: true

ignoreUrlParametersMatching [Array⟨Regex⟩]

sw-precache finds matching cache entries by doing a comparison with the full request URL. It's common for sites to support URL query parameters that don't affect the site's content and should be effectively ignored for the purposes of cache matching—one example is the utm_-prefixed parameters used for tracking campaign performance. By default, sw-precache will ignore key=value when key matches any of the regular expressions provided in this option. To ignore all parameters, use [/./]. To take all parameters into account when matching, use [].

Default: [/^utm_/]

importScripts [Array⟨String⟩]

If you'd like to include one or more external scripts as part of the generated service worker code, use this option. The scripts passed in will be passed directly to the importScripts() method.

Default: []

logger [function]

A function used to report back on which resources are being precached and the overall size. Use function() {} if you'd prefer that nothing is logged. Within a gulp script, it's recommended that you use gulp-util and pass in gutil.log.

Default: console.log

maximumFileSizeToCacheInBytes [Number]

Files larger than this size will not be added to the precache list.

Default: 4194304 (2 megabytes)

stripPrefix [String]

Useful when there's a discrepency between the relative path to a local file at build time and the relative URL that the resource will be served from. E.g. if all your local files are under dist/app/ and your web root is also at dist/app/, you'd strip that prefix from the start of each local file's path in order to get the correct relative URL.

Default: ''

staticFileGlobs [Array⟨String⟩]

An array of one or more string patterns that will be passed in to glob. All files matching these globs will be automatically precached by the generated service worker. You'll almost always want to specify something for this.

Default: []

templateFilePath [String]

The path to the file used as the (lo-dash) template to generate service-worker.js. If you need to add in additional functionality to the generated service worker code, it's recommended that you use the importScripts option to include in extra JavaScript code rather than using a different template. But if you do need to change the basic generated service worker code, please make a copy of the original template, modify it locally, and use this option to point to your template file.

Default: service-worker.tmpl (in the directory that this module lives in)

Acknowledgements

Thanks to Sindre Sorhus and Addy Osmani for their advice and code reviews. Jake Archibald was kind enough to review the service worker logic.

License

Apache 2.0 © 2015 Google Inc.

sw-precache's People

Contributors

jeffposnick avatar paradox41 avatar

Watchers

Ralph Yozzo avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.