https://github.com/ostark/cache-holepuncher
A toolkit for pulling dynamic snippets in fully cached sites, a technique called Cache Hole Punching
https://github.com/ostark/cache-holepuncher
Last synced: over 1 year ago
JSON representation
A toolkit for pulling dynamic snippets in fully cached sites, a technique called Cache Hole Punching
- Host: GitHub
- URL: https://github.com/ostark/cache-holepuncher
- Owner: ostark
- License: mit
- Created: 2018-12-11T12:00:30.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-12-30T01:35:19.000Z (over 7 years ago)
- Last Synced: 2025-02-23T02:38:45.175Z (over 1 year ago)
- Language: JavaScript
- Homepage:
- Size: 35.2 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# cache-holepuncher.js
A lightweight dependency-free library for cache hole punching.
Pull dynamic HMTL snippets in fully cached sites with a single line of code. By default the response is cached browser to avoid unnecessary requests.
## Install
```bash
npm install cache-holepuncher
```
or
```bash
yarn add cache-holepuncher
```
If you are constained to a non-module environment (e.g. no bundlers such as webpack), pull the latest version of `cache-holepuncher` from `jsdelivr`.
```html
```
## Basic usage
...
### Get single
```html
empty state
punch_one("/some/endpoint", "single_placeholder_id");
```
### Get multiple
```html
- empty state
- empty state
punch_all(".placeholder", "data-callback-url");
```
### Flush local cache
```js
document.querySelector("form").addEventListener('submit', e => punch_flush());
```
## Advanced usage
```js
import { HolePuncher } from './holepuncher';
let puncher = new HolePuncher(options);
let placeholder = document.getElementById(elementId);
let url = '/some/endpoint';
// do something before fetch
puncher.events.on('before_fetch', e => {
const placeholder = e.detail.context;
placeholder.classList.add('loading');
});
// do something when the data is avaiable
puncher.events.on('fetch_data', e => {
// hide loader
const placeholder = e.detail.context;
const response = e.detail.response.clone();
response.json().then(data => {
placeholder.innerHTML = data.someAttribute;
placeholder.classList.remove('loading');
console.log(data.anotherAttribute)
});
});
// fetch html
puncher.fetch(url, placeholder);
// fetch json
puncher.fetch(url, placeholder, {
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json'
})
});
// register listener that flushes the local cache
document.querySelector("form").addEventListener('submit', e => {
puncher.flush({verbose: true})
});
```