kimlai

kimlai

Hi everyone,

I’m trying to add a service worker to a Phoenix 1.5 app to display an offline page when the user has no network connectivity. To do this I need to cache some static assets (css, fonts and an image) along with the html page itself.

Following this cookbook, I would need something like

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('pre-cache:v1').then(function(cache) {
      return cache.addAll([
        '/css/app.css',
        '/images/logo.svg',
        '/fonts/some-font.woff2',
        '/offline.html',
      ]);
    })
  );
});

Since I’m using Phoenix, my static assets are “digested” using mix phx.digest when the app is deployed to production, so I need to cache the files using their hashed names. I also want the service worker to work locally, where the filenames do not contain a cache-busting hash. I also would like to avoid adding a build step. Something like workbox would require to run their cli after mix phx.digest has run, so it’s quite awkward to make it work in conjunction with webpack to get reloading etc. when working locally (I did something like this in the past and it was not great to work with).

Basically I need a way of getting the name of some assets, with the hash in production, and without the hash locally, which is exactly what Routes.static_path/2 does, and put the result inside a javascript file.

So what I came up with it to generate the service-worker.js file using EEx by doing this:

# router.ex
  scope "/", MyApp do                                                                                         
    get "/service-worker.js", SomeController, :service_worker                                                     
  end  
# some_controller.ex
def service_worker(conn, _) do
  conn
  |> put_resp_content_type("application/javascript")
  |> render("service_worker.js")
end
  # service_worker.js.eex
...
  caches.open("pre-cache:v1").then(cache => cache.addAll([                                                                                                                  
    "<%= Routes.static_path(@conn, "/css/app.css") %>",                                                                                            
    "<%= Routes.static_path(@conn, "/images/logo.svg") %>",
    "<%= Routes.static_path(@conn, "/fonts/some-font.woff2") %>" 
    "/offline.html",                                                    
  ]));   
...     

It seems to work nicely, but I don’t think that I’ve ever seen EEx being used to render anything but html, so I’m wondering if I missed something here (security issues, or a simpler way of doing this).

Thanks!

Showing Posts 1 to 3

03juan

03juan

Hi @kimlai, did you end up using this method successfully as described? I’ve realised the need to re-develop part of my LiveView site as an offline-first app for field work in poor network conditions, so I’d also have to integrate with a front-end framework, local storage and Channels for bidirectional syncing, but that would all be implemented in their own cached scripts as well. Any pitfalls you’ve come across?

lucaong

lucaong

I use the same strategy for the ServiceWorker on an offline-first production Rails + JS application with good results since years. While somewhat uncommon, there is no issue in rendering a JS file with EEx when needed.

Of course, LiveView needs some special care when it comes to offline behavior, and depending on your needs, being it a server-side tech, it might not be the best option if offline-first is a strong requirement.

03juan

03juan

This is quite true. The strategy will be to migrate the architecture from LiveView-centric server side rendering to client-side from Phoenix endpoint (dead view), with Phoenix Channels for the data-synchronization and event-handling reactivity while the app is online, and a light-weight templating engine for the DOM rendering (currently trialling lit-html).

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews