Skip to content

Instantly share code, notes, and snippets.

@PierBover
Created June 21, 2022 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PierBover/ad5f51103c5280e98b5e905176038327 to your computer and use it in GitHub Desktop.
Save PierBover/ad5f51103c5280e98b5e905176038327 to your computer and use it in GitHub Desktop.
Bfcache action for Svelte
const elements = [];
const events = [];
window.addEventListener('pageshow', (event) => {
const navigationType = window.performance.getEntriesByType('navigation')[0].type;
if (navigationType !== 'back_forward') return;
elements.forEach((element, index) => {
element.dispatchEvent(new Event(events[index], {
bubbles: true,
cancelable: true
}));
});
});
export default function (node, eventName) {
elements.push(node);
events.push(eventName);
return {
destroy () {
const index = elements.getIndexOf(node);
elements.splice(index, 1);
events.splice(index, 1);
}
};
}
<select use:bfcacheEvent={'change'}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment