diff-replacer
v0.0.3
Published
High-performance innerHTML replacement with smart DOM diffing. Tiny, fast, and preserves element state (focus, inputs, scroll).
Downloads
29
Maintainers
Readme
diff-replacer 🚀
diff-replacer is a lightweight TypeScript utility that brings DOM Diffing to the standard innerHTML setter experience. It extends the Element prototype with a .replaceHTML property that updates only the changed parts of the DOM tree.
✨ Why use this?
The standard element.innerHTML = '...' is destructive. It wipes out the existing DOM nodes and recreates them from scratch, which causes:
- ❌ Loss of focus in
<input>,<textarea>, orcontenteditableelements. - ❌ Resetting of scroll positions within overflow containers.
- ❌ Interrupted playback for
<video>and<audio>tags. - ❌ Poor performance when updating large lists or complex layouts.
diff-replacer solves this by using a "smart update" strategy. It parses your HTML string and "morphs" the current DOM to match it, preserving state and identity where possible.
📦 Installation
npm install diff-replacer🚀 Usage
Simply import the package once at the entry point of your application (e.g., main.ts or app.ts). It will automatically extend the global Element prototype.
import 'diff-replacer';
const container = document.querySelector('#app') as HTMLElement;
// Initial render
container.replaceHTML = `
<div class="profile">
<h1>User Profile</h1>
<input type="text" placeholder="Enter your name...">
</div>
`;
// Smart update later
setTimeout(() => {
// Only the <h1> text changes.
// The <input> remains untouched, preserving focus and typed text!
container.replaceHTML = `
<div class="profile">
<h1>Updated Profile</h1>
<input type="text" placeholder="Enter your name...">
</div>
`;
}, 2000);🛠 Features
- Native DX: Feels just like using
innerHTML. - State Preservation: Keeps inputs focused and scroll positions intact.
- TypeScript First: Full type definitions for
Element.replaceHTML. - Vite Optimized: Built with Vite for modern web development.
- Zero Config: Just import and go.
📖 How it works
Under the hood, diff-replacer uses the browser's native DOMParser to turn your string into a temporary DOM tree. It then utilizes the battle-tested morphdom algorithm to perform a deep comparison and patch the live DOM with the minimum number of changes.
