Offline and instant loads
Read datapages first for the build loop, hard rules and naming conventions.
modules/offline serves a service worker and adds registration to HTML responses. Handlers write its cache through the pageCache datapages.PageCacheWriter parameter:
- Snapshots (
Set): served only while the browser is offline. - Shims (
SetShim): served online too, at once, then replaced by the live page.
The worker runs only in a secure context (HTTPS or localhost). Everywhere else the API does nothing.
Configure the module
Declaring PageOffline generates a WithOffline option with that page's route:
// PageOffline is /offline
type PageOffline struct{ App *App }
func (PageOffline) GET(r *http.Request) (body datapages.Component, err error) {
return pageOffline(), nil
}
opts := []datapages.ServerOption{
// Self-host Datastar: the CDN is unreachable offline.
datapages.WithDatastarJS(assets.Path("datastar.js")),
datapagesgen.WithOffline(app.OfflineConfig()),
}
// OfflineWorkerVersion identifies the installed worker and its cache. Increment
// it after a Datapages upgrade or a change to Assets, ExcludePaths,
// CrossOriginDestinations, OfflineClass, or PageOffline. Changes to Assets or
// PageOffline require a new installation because the worker fetches them only
// during installation.
const OfflineWorkerVersion = 1
func OfflineConfig() offline.Config {
return offline.Config{
WorkerVersion: OfflineWorkerVersion,
// Precache the files required to render cached pages offline.
Assets: []string{
assets.Path("style.css"), assets.Path("datastar.js"),
},
}
}
For shims without PageOffline, install the module directly:
offline.WithServiceWorker("", offline.Config{WorkerVersion: 1})
| offline.Config field | default |
| ---------------------- | ------- |
| WorkerVersion | 1; increment after a Datapages upgrade or a change to Assets, ExcludePaths, CrossOriginDestinations, OfflineClass, or PageOffline |
| ScriptURL | /service-worker.js; the scope is the whole origin either way |
| Assets | none; files cached during installation |
| OfflineClass | is-offline, toggled on <html> while offline |
| CrossOriginDestinations | image, style, script, font; empty non-nil disables |
| ExcludePaths | none; same-origin prefixes never cached |
Style offline state in CSS, no Go code:
.is-offline [data-needs-network] { opacity: .5; pointer-events: none }
Register a compressing middleware before WithOffline. Middleware runs in the order it is given, and the offline middleware rewrites the HTML it receives. A response that already carries a Content-Encoding passes through unchanged, which leaves the page without the worker registration.
Offline support writes inline scripts: the connectivity script, the worker registration and queued cache writes. Each script uses the nonce from WithCSPNonce. WithOffline reads the nonce when each request arrives, independent of option order. Set offline.Config.CSPNonce to use a different nonce for these scripts.
When offline.Config.CSPNonce is nil, offline.WithServiceWorker uses the nonce from WithCSPNonce. Calling offline.Middleware through datapages.WithMiddleware does not copy the server nonce. A nonce-only policy blocks the middleware scripts.
A cached page is rendered once and replayed. It cannot contain a valid per-response nonce. Its shim hydration trigger and connectivity script are written without one. The service worker provides no policy header, and the browser does not require a nonce. A Content-Security-Policy in a meta element would block those scripts.
PageOffline
PageOffline is reserved like PageError404 and PageError500. The worker caches it during installation and returns it for an uncached URL while offline. It renders with a zero Session. Datapages supplies a minimal default.
The pageCache parameter
The parameter is optional on GET methods and on page or *App actions.
| method | effect |
| ------ | ------ |
| Version() | the version the client holds for this request's URL, 0 if none |
| Set(url, body, version) | cache body for url, served only while offline |
| SetShim(url, body, version) | cache body for url, served online too |
| Clear(url) | remove one entry |
| ClearAll() | remove every page cache entry |
url comes from the generated href package. Writes remain queued until the handler returns without error. The worker then applies them together, with ClearAll first.
Version() covers this URL only. Caching any other URL is therefore unconditional.
Snapshots
func (p PagePost) GET(
r *http.Request,
pageCache datapages.PageCacheWriter,
path datapages.Path[struct {
Slug string `path:"slug"`
}],
) (body datapages.Component, err error) {
post, ok := p.App.Post(path.Values.Slug)
if !ok {
return nil, datapages.ErrNotFound
}
if ver := postVersion(post); pageCache.Version() != ver {
pageCache.Set(href.PagePost(post.Slug), postOffline(post), ver)
}
return postPage(post), nil
}
A snapshot need not match the live body. It is what the user sees with no network: leave out what cannot work there.
A GET can cache its own page when visited. An action can cache other URLs, such as ticket pages created by a purchase.
Shims
A shim renders the navigation and layout with placeholders for slow content. The worker returns the cached shim immediately and fetches the live page in parallel. Datapages adds the trigger that replaces the shim's head and body through Datastar. The shim contains no Datastar attributes.
A shim renders with no session and contains no CSRF script. Do not put actions in the placeholder content.
// shimVersion changes when the placeholder markup changes.
const shimVersion = 1
func (p PageIndex) GET(
r *http.Request, pageCache datapages.PageCacheWriter,
) (body datapages.Component, err error) {
rows, err := p.App.Rows(r.Context())
if err != nil {
return nil, err
}
if pageCache.Version() != shimVersion {
pageCache.SetShim(href.PageIndex(), shim(len(rows)), shimVersion)
}
return indexPage(rows), nil
}
A shim is also shown online. It must not make an offline-only claim. If the live request fails, the shim remains visible.
Rules
- Pass the page body, not a document. Datapages adds the same
<head>, stylesheets and Datastar bundle used by a live page. Adding<!DOCTYPE html>to the body would nest one document inside another. - A cached page is only as complete as its assets. Its stylesheets, scripts, fonts and images must be cached too.
Config.Assetsis precached on install. Everything else is cached on its first load while online: same-origin files other than what Datastar requests (actions, hydrates and event streams always come from the network) and other thanConfig.ExcludePaths, plus cross-origin requests whose destination is inConfig.CrossOriginDestinations. An asset that is neither listed nor ever loaded online is missing offline. A cached same-origin asset is refreshed behind the copy it serves: a file redeployed at the same URL lands on the next visit, with noWorkerVersionbump. - Version by everything the body depends on. A constant version caches once and never refreshes. Include the content state, such as an item count or an ownership flag.
```go
// The ownership button changes, so ownership is part of the version.
ver := snapshotVersion(session.UserID, owned) // For example, an FNV-1a hash.
if pageCache.Version() != ver {
pageCache.Set(href.PagePost(slug), postOffline(post), ver)
}
```
- Use
!=, not<, for an unordered version key such as a hash.<re-caches only on an increase and silently keeps a stale entry. - Use
ClearAll()when one change invalidates many pages. Examples include locale, permission and session changes. Entries return only after a handler callsSetagain. CallClearAll()during sign-in and sign-out. - Update invalidated entries. A page cached by its
GETupdates on the next online visit. An action that changes another cached page should callSetfor that page.
What may be cached
A snapshot is stored in the browser's cache for the origin. Any script on that origin can read it. It is not bound to a session and stays readable after the visitor signs out.
- Call
ClearAll()from the sign-in and sign-out handlers. OnlyClearandClearAllremove an entry. - A redirect waits up to 500ms for the worker. A tab closed before that keeps its old entries.
- Leave out what must not outlive the session: a payment detail, a token, another person's data. Cache the page without it.
- A snapshot renders with the zero session. A template that branches on the session takes the signed-out branch. Put the visitor in the version key when a snapshot has to differ per visitor.
Delivery
The generated code picks how queued writes reach the worker from the handler signature, first row that matches. An action on *App follows the same rules as one on a page.
| handler | delivery |
| ------- | -------- |
| GET | embedded in the page HTML and applied on load |
| action taking sse | sent over that stream |
| action returning redirect | sent in its text/javascript response; navigation waits up to 500ms for the worker. This applies even when the action also returns a body |
| action returning only a body | embedded in the rendered document |
| action returning neither | sent over an SSE stream opened for that purpose, readable only by a Datastar request |
newSession and closeSession cannot be combined with sse. Sign-in and sign-out therefore take pageCache and return a redirect. Navigation waits up to 500ms for the worker to apply ClearAll before loading the destination.
<!-- written by datapages v0.10.0 -->