Skip to content

Instantly share code, notes, and snippets.

@osbre
Created July 20, 2025 19:54
Show Gist options
  • Save osbre/6fbafda85c3066cbfab4644cef7b3103 to your computer and use it in GitHub Desktop.
Save osbre/6fbafda85c3066cbfab4644cef7b3103 to your computer and use it in GitHub Desktop.
Like hx-boost or Tuborlinks. Just 3.2 kB minified+gzipped. Optional `data-no-morph`
<script src="https://unpkg.com/[email protected]"></script>
<script>
const morphTo = async (url, opts = {}) => {
const res = await fetch(url, { headers: { 'X-Requested-With': 'Idiomorph' }, ...opts });
const text = await res.text();
const html = new DOMParser().parseFromString(text, 'text/html');
Idiomorph.morph(document.body, html.body, { restoreFocus: true });
};
addEventListener('click', e => {
const a = e.target.closest('a');
if (a && !a.hasAttribute('data-no-morph') && a.origin === location.origin && a.href !== location.href) {
e.preventDefault();
morphTo(a.href);
history.pushState(null, '', a.href);
}
});
addEventListener('submit', e => {
const f = e.target.closest('form');
if (f && !f.hasAttribute('data-no-morph')) {
e.preventDefault();
const fd = new FormData(f);
const method = (f.method || 'GET').toUpperCase();
const url = f.action || location.href;
if (method === 'GET') {
const q = new URLSearchParams(fd).toString();
morphTo(url + '?' + q);
history.pushState(null, '', url + '?' + q);
} else {
morphTo(url, { method, body: fd });
}
}
});
addEventListener('popstate', () => morphTo(location.href));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment