├── .gitignore ├── CODE_OF_CONDUCT.md ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── bin ├── console └── setup ├── jekyll-offline.gemspec └── lib ├── jekyll-offline.rb ├── jekyll-offline ├── offline.rb └── version.rb └── sw.js /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /Gemfile.lock 4 | /_yardoc/ 5 | /coverage/ 6 | /doc/ 7 | /pkg/ 8 | /spec/reports/ 9 | /tmp/ 10 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. 4 | 5 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion. 6 | 7 | Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. 8 | 9 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. 10 | 11 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. 12 | 13 | This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/) 14 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # Specify your gem's dependencies in jekyll-offline.gemspec 4 | gemspec 5 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Jeremia Kimelman 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jekyll-offline 2 | 3 | ruby gem/jekyll plugin to use service workers and make site content available offline. When visitors load a site, the service worker will be registered and cache content on their device, enabling people to read the content offline/without a network connection. 4 | 5 | Many thanks to @gauntface and @jakearchibald for two great resources on Service Workers: 6 | * [HTML 5 Rocks service worker tutorial]( http://www.html5rocks.com/en/tutorials/service-worker/introduction/) 7 | * [Offline cookbook](https://jakearchibald.com/2014/offline-cookbook) 8 | 9 | ## Installation 10 | 11 | Add this line to your application's Gemfile: 12 | 13 | ```ruby 14 | group 'jekyll-plugins' do 15 | gem 'jekyll-offline', :git => 'git://github.com/jeremiak/jekyll-offline.git' 16 | end 17 | ``` 18 | 19 | And add this to your `_config.yml`: 20 | 21 | ```ruby 22 | gems: ['jekyll-offline'] 23 | ``` 24 | 25 | And then execute: 26 | 27 | $ bundle install 28 | 29 | ## Usage 30 | 31 | The plugin does most of the work for you, but you have to initialize the service worker on the page with the `{% register_service_worker %}` liquid tag. It is generally a good idea to put this near the bottom of your default layout so that all pages have it. 32 | 33 | You can use a variety of strategies to respond to requests. These strategies were pulled from [the offline cookbook](https://jakearchibald.com/2014/offline-cookbook/#serving-suggestions-responding-to-requests) with minimal changes. 34 | 35 | Configure `jekyll-offline` to use a given strategy by adding the following to your `_config.yml`: 36 | ``` 37 | ... 38 | offline: 39 | strategy: << whatever you want >> 40 | ``` 41 | 42 | You can supply the following options as the value for `strategy`: 43 | * `cache-only` 44 | * `network-only` 45 | * `cache-first-network-fallback` 46 | * `network-first-cache-fallback` 47 | * `cache-network-race` 48 | * `cache-then-network` (default) 49 | 50 | ## Contributing 51 | 52 | Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/jekyll-offline. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct. 53 | 54 | 55 | ## License 56 | 57 | The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). 58 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require "bundler/setup" 4 | require "jekyll/offline" 5 | 6 | # You can add fixtures and/or initialization code here to make experimenting 7 | # with your gem easier. You can also use a different console, if you like. 8 | 9 | # (If you use this, don't forget to add pry to your Gemfile!) 10 | # require "pry" 11 | # Pry.start 12 | 13 | require "irb" 14 | IRB.start 15 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | 5 | bundle install 6 | 7 | # Do any other automated setup that you need to do here 8 | -------------------------------------------------------------------------------- /jekyll-offline.gemspec: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | lib = File.expand_path('../lib', __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require 'jekyll-offline/version' 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = "jekyll-offline" 8 | spec.version = JekyllOffline::VERSION 9 | spec.authors = ["Jeremia Kimelman"] 10 | spec.email = ["jbkimelman@gmail.com"] 11 | 12 | spec.summary = %q{jekyll plugin to use service workers and make site content available offline} 13 | spec.homepage = "https://github.com/jeremiak/jekyll-offline" 14 | spec.license = "MIT" 15 | 16 | # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or 17 | # delete this section to allow pushing this gem to any host. 18 | if spec.respond_to?(:metadata) 19 | spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'" 20 | else 21 | raise "RubyGems 2.0 or newer is required to protect against public gem pushes." 22 | end 23 | 24 | spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } 25 | spec.bindir = "exe" 26 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } 27 | spec.require_paths = ["lib"] 28 | 29 | spec.add_development_dependency "bundler", "~> 1.10" 30 | spec.add_development_dependency "rake", "~> 10.0" 31 | end 32 | -------------------------------------------------------------------------------- /lib/jekyll-offline.rb: -------------------------------------------------------------------------------- 1 | require_relative 'jekyll-offline/offline' 2 | require_relative 'jekyll-offline/version' 3 | -------------------------------------------------------------------------------- /lib/jekyll-offline/offline.rb: -------------------------------------------------------------------------------- 1 | require 'jekyll' 2 | require 'liquid' 3 | 4 | module JekyllOffline 5 | class JavaScriptFile < Jekyll::Page 6 | def read_yaml(*) 7 | @data ||= {} 8 | end 9 | end 10 | 11 | class ServiceWorkerGenerator < Jekyll::Generator 12 | def generate(site) 13 | service_worker_source = File.join(File.dirname(__FILE__), '..', 'sw.js'); 14 | service_worker_file = JavaScriptFile.new(site, File.dirname(__FILE__), '', 'sw.js') 15 | service_worker_file.content = File.read service_worker_source 16 | service_worker_file.data["layout"] = nil 17 | service_worker_file.render({}, site.site_payload) 18 | site.pages << service_worker_file 19 | end 20 | end 21 | 22 | class ServiceWorkerRegistrationTag < Liquid::Tag 23 | def render(context) 24 | html = '' 25 | html << '' 34 | html 35 | end 36 | end 37 | 38 | end 39 | 40 | Liquid::Template.register_tag('register_service_worker', JekyllOffline::ServiceWorkerRegistrationTag) 41 | -------------------------------------------------------------------------------- /lib/jekyll-offline/version.rb: -------------------------------------------------------------------------------- 1 | module JekyllOffline 2 | VERSION = "0.1.0" 3 | end 4 | -------------------------------------------------------------------------------- /lib/sw.js: -------------------------------------------------------------------------------- 1 | var urlsToCache = []; 2 | 3 | {% for post in site.posts %} 4 | urlsToCache.push("{{ post.permalink }}"); 5 | {% endfor %} 6 | 7 | {% for page in site.pages %} 8 | {% if page.permalink %} 9 | urlsToCache.push("{{ page.permalink }}"); 10 | {% endif %} 11 | 12 | {% if page.url %} 13 | urlsToCache.push("{{ page.url }}"); 14 | {% endif %} 15 | {% endfor %} 16 | 17 | var CACHE_NAME = '{{ site.title | slugify }}-cache-v1'; 18 | 19 | self.addEventListener('install', function(event) { 20 | // Perform install steps 21 | event.waitUntil(caches.open(CACHE_NAME).then(function(cache) { 22 | return cache.addAll(urlsToCache); 23 | }).catch(function(err) { 24 | console.log('cache add err', err); 25 | })); 26 | }); 27 | 28 | self.addEventListener('fetch', function(event) { 29 | event.respondWith( 30 | caches.open(CACHE_NAME).then(function(cache) { 31 | return cache.match(event.request).then(function (response) { 32 | return response || fetch(event.request).then(function(response) { 33 | cache.put(event.request, response.clone()); 34 | return response; 35 | }); 36 | }); 37 | }) 38 | ); 39 | }); 40 | 41 | // strategies from the offline cookbook by jake archibald 42 | // https://jakearchibald.com/2014/offline-cookbook/#serving-suggestions-responding-to-requests 43 | 44 | {% assign strategy = site.offline.strategy | default: 'cache-then-network' %} 45 | {% if strategy == 'cache-only' %} 46 | self.addEventListener('fetch', function(event) { 47 | // If a match isn't found in the cache, the response 48 | // will look like a connection error 49 | event.respondWith(caches.match(event.request)); 50 | }); 51 | {% elsif strategy == 'network-only' %} 52 | self.addEventListener('fetch', function(event) { 53 | event.respondWith(fetch(event.request)); 54 | // or simply don't call event.respondWith, which 55 | // will result in default browser behaviour 56 | }); 57 | {% elsif strategy == 'cache-first-network-fallback' %} 58 | self.addEventListener('fetch', function(event) { 59 | event.respondWith( 60 | caches.match(event.request).then(function(response) { 61 | return response || fetch(event.request); 62 | }) 63 | ); 64 | }); 65 | {% elsif strategy == 'network-first-cache-fallback' %} 66 | self.addEventListener('fetch', function(event) { 67 | event.respondWith( 68 | fetch(event.request).catch(function() { 69 | return caches.match(event.request); 70 | }) 71 | ); 72 | }); 73 | {% elsif strategy == 'cache-network-race' %} 74 | // Promise.race is no good to us because it rejects if 75 | // a promise rejects before fulfilling. Let's make a proper 76 | // race function: 77 | function promiseAny(promises) { 78 | return new Promise((resolve, reject) => { 79 | // make sure promises are all promises 80 | promises = promises.map(p => Promise.resolve(p)); 81 | // resolve this promise as soon as one resolves 82 | promises.forEach(p => p.then(resolve)); 83 | // reject if all promises reject 84 | promises.reduce((a, b) => a.catch(() => b)) 85 | .catch(() => reject(Error("All failed"))); 86 | }); 87 | }; 88 | 89 | self.addEventListener('fetch', function(event) { 90 | event.respondWith( 91 | promiseAny([ 92 | caches.match(event.request), 93 | fetch(event.request) 94 | ]) 95 | ); 96 | }); 97 | {% elsif strategy == 'cache-then-network' %} 98 | self.addEventListener('fetch', function(event) { 99 | event.respondWith( 100 | caches.open(CACHE_NAME).then(function(cache) { 101 | return fetch(event.request).then(function(response) { 102 | cache.put(event.request, response.clone()); 103 | return response; 104 | }); 105 | }) 106 | ); 107 | }); 108 | {% endif %} 109 | --------------------------------------------------------------------------------