Search code examples
progressive-web-apps

Handle offline page resources from sub directories


I'm working on a PWA testing it on localhost Xampp server. Here's my folder structure

/
  |- css
  |   |- style.css
  |- sub
  |   |- other.html
  |- index.html
  |- manifest.webmanifest
  |- service-worker.js
  |- offline.html

offline.html has a link to css file css/style.css in the head tag. When I'm at the URL localhost/index.html and I go offline, the offline page loads perfectly. But when I go to localhost/sub/other.html and go offline, the style.css can not load (it is cached).

The browser is looking for the file in localhost/sub/css/style.css. So I guess the location in offline.html for style.css needs to be ../css/style.css.

How do I handle this location problem with sub directories?


Solution

  • If the contents of your /offline.html file are used to fulfill offline navigations for any arbitrary URL, you've got two options to ensure that your subresources are loaded properly:

    • Always use absolute URLs when specifying the src or href of subresources. In other words, use <link href="/css/style.css" ...> instead of <link href="css/style.css" ...>.

    • Add a <base href="/"> tag to your offline.html HTML, which will cause all subresource URLs to be resolved relative to /.