Slide 1

Slide 1 text

Progressive Web Apps for R a ils developers Emm a nuel H a yford R a ils Ch a ngelog Podc a st Host @si a w23

Slide 2

Slide 2 text

App a v a il a bility with fl a ky/no internet connections Push Noti fi c a tions F a st lo a d times No middlem a n with a pp downlo a ds/inst a ll a tion S a ve money on dedic a ted n a tive a pp dev te a m Why should you consider PWAs with R a ils?

Slide 3

Slide 3 text

Why should consider PWAs with R a ils? source: https://www.pw a st a ts.com

Slide 4

Slide 4 text

“I don’t w a nn a use Apple stu ff a nymore… the fi n a l str a w w a s when Apple s a id ‘we’re gonn a pull PWAs outt a Europe.’” - DHH vi a How About Tomorrow Podc a st

Slide 5

Slide 5 text

PWA Requirements Service worker Secure context Web a pplic a tion m a nifest

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

Slide 12

Slide 12 text

<%= tag.link rel: "manifest", href: pwa_manifest_path(format: :json) %>

Slide 13

Slide 13 text

# config/routes.rb Rails.application.routes.draw do end

Slide 14

Slide 14 text

# config/routes.rb Rails.application.routes.draw do get "manifest" => "rails/pwa#manifest", as: :pwa_manifest get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker end

Slide 15

Slide 15 text

// app/javascript/application.js if ("serviceWorker" in navigator) { }

Slide 16

Slide 16 text

// app/javascript/application.js if ("serviceWorker" in navigator) { // Register a service worker hosted at the root of the // app using the default scope. navigator.serviceWorker.register("/service-worker.js") }

Slide 17

Slide 17 text

// app/javascript/application.js if ("serviceWorker" in navigator) { // Register a service worker hosted at the root of the // app using the default scope. navigator.serviceWorker.register("/service-worker.js").then( (registration) => { console.log("Service worker registration succeeded:", registration); } }

Slide 18

Slide 18 text

// app/javascript/application.js if ("serviceWorker" in navigator) { // Register a service worker hosted at the root of the // app using the default scope. navigator.serviceWorker.register("/service-worker.js").then( (registration) => { console.log("Service worker registration succeeded:", registration); }, (error) => { console.error(`Service worker registration failed: ${error}`); } ); } }

Slide 19

Slide 19 text

// app/javascript/application.js if ("serviceWorker" in navigator) { // Register a service worker hosted at the root of the // app using the default scope. navigator.serviceWorker.register("/service-worker.js").then( (registration) => { console.log("Service worker registration succeeded:", registration); }, (error) => { console.error(`Service worker registration failed: ${error}`); } ); } else { console.error("Service workers are not supported."); }

Slide 20

Slide 20 text

Service Worker Lifecycle

Slide 21

Slide 21 text

O ffl ine & Perform a nt PWAs Cache API HTTP Cache Fine-grained, programmatic control over what gets cached, how it's cached, and when it's updated/ deleted. The browser's HTTP cache is managed automatically based on HTTP headers (Cache-Control, Expires, ETag, etc.) provided by the server. Provides a JavaScript interface to interact with cached responses directly within the service worker. JavaScript running in the web page cannot directly access or manipulate the contents of the HTTP cache. Caches are scoped to the origin and the specific service worker, ensuring isolation between different PWAs. The HTTP cache is shared across the entire browser for a given user and origin. It is not scoped to individual applications or service workers. Offers reliable storage intended for offline use, retaining resources until the developer removes them or the browser's storage quota is exceeded. Doesn't guarantee availability when offline, especially if resources are not fresh according to cache validation rules.

Slide 22

Slide 22 text

// app/views/pwa/service-worker.js self.addEventListener("install", (event) => { });

Slide 23

Slide 23 text

// app/views/pwa/service-worker.js self.addEventListener("install", (event) => { event.waitUntil( ); });

Slide 24

Slide 24 text

// app/views/pwa/service-worker.js self.addEventListener("install", (event) => { event.waitUntil( caches.open("v1") ); });

Slide 25

Slide 25 text

// app/views/pwa/service-worker.js self.addEventListener("install", (event) => { event.waitUntil( caches.open("v1") .then((cache) => ), ); });

Slide 26

Slide 26 text

// app/views/pwa/service-worker.js self.addEventListener("install", (event) => { event.waitUntil( caches.open("v1") .then((cache) => cache.addAll([ "/some.html", "/application.js", "/offline.html", ]), ), ); });

Slide 27

Slide 27 text

// app/views/pwa/service-worker.js self.addEventListener("fetch", (event) => { });

Slide 28

Slide 28 text

// app/views/pwa/service-worker.js self.addEventListener("fetch", (event) => { event.respondWith( ); });

Slide 29

Slide 29 text

// app/views/pwa/service-worker.js self.addEventListener("fetch", (event) => { event.respondWith( caches.match(event.request).then((response) => { }), ); });

Slide 30

Slide 30 text

// app/views/pwa/service-worker.js self.addEventListener("fetch", (event) => { event.respondWith( caches.match(event.request).then((response) => { if (response !== undefined) { return response; } }), ); });

Slide 31

Slide 31 text

// app/views/pwa/service-worker.js self.addEventListener("fetch", (event) => { event.respondWith( caches.match(event.request).then((response) => { if (response !== undefined) { return response; } else { return fetch(event.request) .then((response) => { let responseClone = response.clone(); caches.open("v1").then((cache) => { cache.put(event.request, responseClone); }); return response; }) } }), ); });

Slide 32

Slide 32 text

// app/views/pwa/service-worker.js self.addEventListener("fetch", (event) => { event.respondWith( caches.match(event.request).then((response) => { if (response !== undefined) { return response; } else { return fetch(event.request) .then((response) => { let responseClone = response.clone(); caches.open("v1").then((cache) => { cache.put(event.request, responseClone); }); return response; }) .catch(() => caches.match("/offline.html")); } }), ); });

Slide 33

Slide 33 text

Why did the PWA bring a ladder to the apps party? Because it wanted to take things of fl ine—but still be up to date!

Slide 34

Slide 34 text

BackgroundSync API IndexedDB The BackgroundSync API allows web apps to delay sending data to the server until the device is online, with the service worker handling it in the background. IndexedDB is a low-level, large-scale, NoSQL storage system that allows storing structured data in the user's browser. IndexedDB Libraries localForage, Dexie.js, idb-keyval, PouchDb

Slide 35

Slide 35 text

import { set, get } from 'idb-keyval';

Slide 36

Slide 36 text

import { set, get } from 'idb-keyval'; set('hello', 'world') .then(() => console.log('It worked!')) .catch((err) => console.log('It failed!', err));

Slide 37

Slide 37 text

import { set, get } from 'idb-keyval'; set('hello', 'world') .then(() => console.log('It worked!')) .catch((err) => console.log('It failed!', err)); // logs: "world" get('hello').then((val) => console.log(val));

Slide 38

Slide 38 text

<%= form_with(url: "/blogs", method: :post, id: "blogForm") do %>
<%= label_tag :title, "Title:" %> <%= text_field_tag :title, nil, required: true %>
<%= label_tag :content, "Content:" %> <%= text_area_tag :content, nil, required: true %>
<%= submit_tag "Submit" %>
<% end %>

Slide 39

Slide 39 text

// app/javascript/application.js if ('serviceWorker' in navigator) { }

Slide 40

Slide 40 text

// app/javascript/application.js if ('serviceWorker' in navigator && 'SyncManager' in window) { }

Slide 41

Slide 41 text

// app/javascript/application.js if ('serviceWorker' in navigator && 'SyncManager' in window) { navigator.serviceWorker.register('/service-worker.js') .then(registration => { // ... }) .catch(error => { // ... }); } else { // ... }

Slide 42

Slide 42 text

// Function to save blog to IndexedDB via idb-keyval const saveBlogForSync = (blog) => { }; // Function to send blog data const sendBlog = (blog) => { }; // app/javascript/application.js

Slide 43

Slide 43 text

// Function to save blog to IndexedDB via idb-keyval const saveBlogForSync = (blog) => { idbKeyval.set('syncBlog', blog) }; // Function to send blog data const sendBlog = (blog) => { }; // app/javascript/application.js

Slide 44

Slide 44 text

// Function to save blog to IndexedDB via idb-keyval const saveBlogForSync = (blog) => { idbKeyval.set('syncBlog', blog) .then(() => { // Register for background sync return navigator.serviceWorker.ready; }) .then(registration => registration.sync.register('sync-blog')) .catch(error => { console.error('Sync registration failed:', error); }); }; // Function to send blog data const sendBlog = (blog) => { }; // app/javascript/application.js

Slide 45

Slide 45 text

// Function to save blog to IndexedDB via idb-keyval const saveBlogForSync = (blog) => { idbKeyval.set('syncBlog', blog) .then(() => { // Register for background sync return navigator.serviceWorker.ready; }) .then(registration => registration.sync.register('sync-blog')) .catch(error => { console.error('Sync registration failed:', error); }); }; // Function to send blog data const sendBlog = (blog) => { if (navigator.onLine) { // Send blog data immediately if online fetch('/blogs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(blog) }) } else { // If offline, save blog for background sync saveBlogForSync(blog); } }; // app/javascript/application.js

Slide 46

Slide 46 text

// app/javascript/application.js document.getElementById('blogForm').addEventListener('submit', (event) => { event.preventDefault(); });

Slide 47

Slide 47 text

// app/javascript/application.js document.getElementById('blogForm').addEventListener('submit', (event) => { event.preventDefault(); const blog = { title: document.getElementById('title').value, content: document.getElementById('content').value }; });

Slide 48

Slide 48 text

// app/javascript/application.js document.getElementById('blogForm').addEventListener('submit', (event) => { event.preventDefault(); const blog = { title: document.getElementById('title').value, content: document.getElementById('content').value }; sendBlog(blog); });

Slide 49

Slide 49 text

// app/javascript/application.js document.getElementById('blogForm').addEventListener('submit', (event) => { event.preventDefault(); const blog = { title: document.getElementById('title').value, content: document.getElementById('content').value }; sendBlog(blog); }); // Function to send blog data const sendBlog = (blog) => { if (navigator.onLine) { fetch('/blogs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(blog) }) } else { saveBlogForSync(blog); } };

Slide 50

Slide 50 text

// app/views/pwa/service-worker.js importScripts('https://url/to/idb-keyval.min.js'); self.addEventListener('sync', (event) => { });

Slide 51

Slide 51 text

// app/views/pwa/service-worker.js importScripts('https://url/to/idb-keyval.min.js'); self.addEventListener('sync', (event) => { if (event.tag === 'sync-blog') { } });

Slide 52

Slide 52 text

// app/views/pwa/service-worker.js importScripts('https://url/to/idb-keyval.min.js'); self.addEventListener('sync', (event) => { if (event.tag === 'sync-blog') { event.waitUntil( idbKeyval.get('syncBlog') ); } });

Slide 53

Slide 53 text

// app/views/pwa/service-worker.js importScripts('https://url/to/idb-keyval.min.js'); self.addEventListener('sync', (event) => { if (event.tag === 'sync-blog') { event.waitUntil( idbKeyval.get('syncBlog') .then(blog => { if (blog) { return fetch('/blogs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(blog) }) .then(response => { if (response.ok) { } throw new Error('Network response was not ok'); }); } }) ); } });

Slide 54

Slide 54 text

// app/views/pwa/service-worker.js importScripts('https://url/to/idb-keyval.min.js'); self.addEventListener('sync', (event) => { if (event.tag === 'sync-blog') { event.waitUntil( idbKeyval.get('syncBlog') .then(blog => { if (blog) { return fetch('/blogs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(blog) }) .then(response => { if (response.ok) { return idbKeyval.delete('syncBlog'); } throw new Error('Network response was not ok'); }); } }) ); } });

Slide 55

Slide 55 text

// app/views/pwa/service-worker.js importScripts('https://url/to/idb-keyval.min.js'); self.addEventListener('sync', (event) => { if (event.tag === 'sync-blog') { event.waitUntil( idbKeyval.get('syncBlog') .then(blog => { if (blog) { return fetch('/blogs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(blog) }) .then(response => { if (response.ok) { return idbKeyval.delete('syncBlog'); } throw new Error('Network response was not ok'); }); } }) .catch(error => { console.error('Sync failed:', error); }) ); } });

Slide 56

Slide 56 text

# app/controllers/blogs_controller.rb class BlogsController < ApplicationController def create @blog = Blog.new(blog_params) if @blog.save render json: { message: 'Blog created successfully' }, status: :created else render json: { message: 'Failed to create blog' }, status: :unprocessable_entity end end private def blog_params params.require(:blog).permit(:title, :content) end end

Slide 57

Slide 57 text

function createBlogDatabase() { // Define the database name and version var dbName = 'BlogDB'; var dbVersion = 1; // Increment this value to trigger onupgradeneeded for future upgrades // This will create or open dbName var request = indexedDB.open(dbName, dbVersion); // Handle the onupgradeneeded event to create the object store and indexes request.onupgradeneeded = function (event) { var db = event.target.result; // Checks if the 'blogs' object store already exists if (!db.objectStoreNames.contains('blogs')) { // Creates the 'blogs' object store with 'id' as the keyPath var objectStore = db.createObjectStore('blogs', { keyPath: 'id', autoIncrement: true }); // You can create indexes for fast querying objectStore.createIndex('title', 'title', { unique: false }); objectStore.createIndex('content', 'content', { unique: false }); objectStore.createIndex('createdAt', 'createdAt', { unique: false }); } }; // Handle the success event. request.onsuccess = function (event) { var db = event.target.result; // if no further operations are needed immediately // close db. db.close(); }; // Handle errors request.onerror = function (event) { console.error('Error opening database:', event.target.errorCode); }; }

Slide 58

Slide 58 text

Diagram courtesy of Apple

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

Th a nk you! Emm a nuel H a yford @si a w23