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

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
water
I’m aware of 2 such projects, are there others? git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
itzmidinesh
Hi all, I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
leoschweizer
Hi, we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
csmr
Hi all, I’m new here and would like to hear peoples views on my Elixir/Phoenix based game-engine! :smiley: Mutonex gamedesign was finish...
New
perzanko
Do we have maintainer of absinthe-graphql/dataloader here? We have a PR that we’d like to merge to the library. Relatively small additive...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
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
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
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews