Debian Codegraph @

www/src/content/extensions/13-hx-history-cache.md

raw symbols SCIP
1 ---
2 title: "hx-history-cache"
3 description: "Cache pages in sessionStorage for instant back/forward"
4 category: "Performance"
5 icon: "icon-[mdi--history]"
6 keywords: ["history", "cache", "sessionStorage", "back", "forward", "navigation"]
7 ---
8
9 The `history-cache` extension replaces htmx's default history handling with a client-side cache stored in `sessionStorage`. When the user navigates back or forward, the extension restores the page instantly from cache instead of fetching from the server.
10
11 ## Installing
12
13 ```html
14 <script src="/path/to/htmx.js"></script>
15 <script src="/path/to/ext/hx-history-cache.js"></script>
16 ```
17
18 ## Usage
19
20 No markup changes are required. Once the script is loaded, all htmx-driven navigation is cached automatically.
21
22 To exclude a page from being saved to the cache, add `hx-history="false"` anywhere in the document:
23
24 ```html
25 <div hx-history="false">
26 <!-- This page will not be saved to the history cache -->
27 </div>
28 ```
29
30 ## Configuration
31
32 All options live under `htmx.config.historyCache` and can be set via a meta tag:
33
34 ```html
35 <meta name="htmx-config" content='{"historyCache": {"size": 20, "refreshOnMiss": true}}'>
36 ```
37
38 To use morphing for smoother restores:
39
40 ```html
41 <meta name="htmx-config" content='{"historyCache": {"swapStyle": "outerMorph"}}'>
42 ```
43
44 | Option | Default | Description |
45 |--------|---------|-------------|
46 | `size` | `10` | Maximum number of pages to keep in the cache. Oldest entries are evicted first. Set to `0` to disable caching entirely. |
47 | `refreshOnMiss` | `false` | When `true`, forces a full page reload if the requested history entry is not in the cache. |
48 | `disable` | `false` | Disables the extension without unloading it. |
49 | `swapStyle` | `"outerSync"` | The htmx swap style used when restoring cached content. Defaults to `outerSync`, which preserves the target element in the DOM (keeping listeners and component state) while syncing its attributes and replacing its children. Use `innerHTML` to replace children only without syncing attributes. Can be set to `"innerMorph"` or `"outerMorph"` for smooth DOM diffing. |
50
51 ## Events
52
53 The extension fires the following events on `document`:
54
55 | Event | Detail | Description |
56 |-------|--------|-------------|
57 | `htmx:history:cache:before:save` | `{ path, target, cache }` | Fired before saving the current page. Return `false` or set `detail.cancelled` to skip saving. Mutations to `path`, `target`, and `cache` are respected. |
58 | `htmx:history:cache:after:save` | `{ path, item, cache }` | Fired after a page is successfully saved. |
59 | `htmx:history:cache:miss` | `{ path, refreshOnMiss }` | Fired when the requested history entry is not in the cache. Set `detail.refreshOnMiss = true` to force a reload. |
60 | `htmx:history:cache:hit` | `{ path, item }` | Fired when a cache entry is found. Return `false` to cancel the cache restore and let htmx fetch from the server instead. |
61 | `htmx:history:cache:restored` | `{ path, item, head }` | Fired after content has been restored from the cache. |
62
63 ### Example: Skipping the cache for specific paths
64
65 ```javascript
66 document.addEventListener('htmx:history:cache:before:save', (evt) => {
67 if (evt.detail.path.startsWith('/admin')) {
68 evt.detail.cancelled = true;
69 }
70 });
71 ```
72
73 ### Example: Handling a cache miss
74
75 ```javascript
76 document.addEventListener('htmx:history:cache:miss', (evt) => {
77 console.log('Cache miss for', evt.detail.path);
78 evt.detail.refreshOnMiss = true; // reload instead of fetching via htmx
79 });
80 ```
81
82 ### Example: Inspecting a cache hit before restore
83
84 ```javascript
85 document.addEventListener('htmx:history:cache:hit', (evt) => {
86 if (isStale(evt.detail.item)) {
87 return false; // bypass cache, let htmx fetch fresh content
88 }
89 });
90 ```
91
92 ## Head Restoration
93
94 By default the extension saves the `<head>` snapshot but does not restore it. Including the [`head-support`](/extensions/hx-head) extension enables full `<head>` restoration on cache hits — styles, scripts, and meta tags are merged back in alongside the body content.
95
96 ```html
97 <script src="/path/to/ext/hx-history-cache.js"></script>
98 <script src="/path/to/ext/hx-head-support.js"></script>
99 ```
100
101 ## How It Works
102
103 1. **Before navigation** (`htmx_before_history_update`): the current page's HTML, `<head>`, title, and scroll position are serialised and written to `sessionStorage`.
104 2. **On back/forward** (`htmx_before_restore_history`): the extension looks up the target path in the cache.
105 - **Hit**: fires `htmx:history:cache:hit`, sets `detail.cancelled = true`, and restores content via `htmx.swap()`. Core never makes a network request. If `head-support` is loaded, the saved `<head>` is also restored via `htmx:history:cache:restored`.
106 - **Miss**: fires `htmx:history:cache:miss`. If `refreshOnMiss` is set the page reloads; otherwise core handles the fetch normally.
107 3. **Cache eviction**: when the cache exceeds `size`, the oldest entry is dropped. If `sessionStorage` is full, entries are dropped from the front until the write succeeds.