Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Progressive Web Apps for Rails developers

Progressive Web Apps for Rails developers

Rails World 2024, Toronto, Ontario, Canada

Explore the evolving world of Progressive Web Apps (PWAs), built with familiar Rails technologies and designed for seamless use in all compatible browsers. Rails 8 promises to simplify PWA development, offering ways to swiftly generate essential PWA scaffolding.

This talk covers PWA basics and Rails 8’s crucial development role. We’ll examine the service worker lifecycle, offline strategies via background sync, and the CacheStorage API for cross-device performance.

Additionally, we’ll investigate local data storage via IndexedDB and exploiting Push Notifications to elevate the user experience to that of native applications.

Emmanuel Hayford

September 27, 2024
Tweet

More Decks by Emmanuel Hayford

Other Decks in Programming

Transcript

  1. 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
  2. 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?
  3. “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
  4. <!-- app/views/layouts/application.html.erb --> <!DOCTYPE html> <html> <head> <%= tag.link rel:

    "manifest", href: pwa_manifest_path(format: :json) %> </head> <body> </body> </html>
  5. # 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
  6. // 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") }
  7. // 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); } }
  8. // 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}`); } ); } }
  9. // 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."); }
  10. 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.
  11. // 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; }) } }), ); });
  12. // 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")); } }), ); });
  13. 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!
  14. 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
  15. import { set, get } from 'idb-keyval'; set('hello', 'world') .then(()

    => console.log('It worked!')) .catch((err) => console.log('It failed!', err));
  16. 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));
  17. <%= form_with(url: "/blogs", method: :post, id: "blogForm") do %> <div>

    <%= label_tag :title, "Title:" %> <%= text_field_tag :title, nil, required: true %> </div> <div> <%= label_tag :content, "Content:" %> <%= text_area_tag :content, nil, required: true %> </div> <div> <%= submit_tag "Submit" %> </div> <% end %>
  18. // app/javascript/application.js if ('serviceWorker' in navigator && 'SyncManager' in window)

    { navigator.serviceWorker.register('/service-worker.js') .then(registration => { // ... }) .catch(error => { // ... }); } else { // ... }
  19. // Function to save blog to IndexedDB via idb-keyval const

    saveBlogForSync = (blog) => { }; // Function to send blog data const sendBlog = (blog) => { }; // app/javascript/application.js
  20. // 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
  21. // 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
  22. // 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
  23. // app/javascript/application.js document.getElementById('blogForm').addEventListener('submit', (event) => { event.preventDefault(); const blog =

    { title: document.getElementById('title').value, content: document.getElementById('content').value }; });
  24. // 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); });
  25. // 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); } };
  26. // 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'); }); } }) ); } });
  27. // 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'); }); } }) ); } });
  28. // 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); }) ); } });
  29. # 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
  30. 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); }; }