JavaScript performance optimization and Web Vitals improvement techniques.
Optimizes JavaScript performance using debounce/throttle, DOM batching, and Web Vitals targets. Use when you see scroll handlers, layout thrashing, or need to improve LCP/INP/CLS metrics.
/plugin marketplace add pluginagentmarketplace/custom-plugin-javascript/plugin install javascript-developer-plugin@pluginagentmarketplace-javascriptThis skill inherits all available tools. When active, it can use any tool Claude has access to.
assets/config.yamlassets/schema.jsonreferences/GUIDE.mdreferences/PATTERNS.mdscripts/validate.py| Metric | Target | Measures |
|---|---|---|
| LCP | < 2.5s | Largest content paint |
| INP | < 200ms | Interaction responsiveness |
| CLS | < 0.1 | Visual stability |
// Debounce - delay until pause
function debounce(fn, delay) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}
// Throttle - limit frequency
function throttle(fn, interval) {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= interval) {
lastCall = now;
fn(...args);
}
};
}
// Usage
window.addEventListener('scroll', throttle(handleScroll, 100));
input.addEventListener('input', debounce(search, 300));
// Batch DOM reads/writes
const heights = elements.map(el => el.offsetHeight); // Read all
elements.forEach((el, i) => el.style.height = heights[i] + 'px'); // Write all
// Use DocumentFragment
const fragment = document.createDocumentFragment();
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
fragment.appendChild(li);
});
list.appendChild(fragment);
// Use requestAnimationFrame
function animate() {
// Update DOM
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
// Dynamic import
const module = await import('./heavy-module.js');
// React lazy
const HeavyComponent = React.lazy(() => import('./Heavy'));
<Suspense fallback={<Spinner />}>
<HeavyComponent />
</Suspense>
// WeakMap for metadata (auto cleanup)
const metadata = new WeakMap();
metadata.set(element, { clicks: 0 });
// Remove event listeners
const controller = new AbortController();
el.addEventListener('click', handler, { signal: controller.signal });
controller.abort(); // Cleanup
// Clear references
let heavyData = loadData();
// When done:
heavyData = null;
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ data: largeArray });
worker.onmessage = (e) => console.log('Result:', e.data);
// worker.js
self.onmessage = (e) => {
const result = processData(e.data);
self.postMessage(result);
};
// Mark and measure
performance.mark('start');
doWork();
performance.mark('end');
performance.measure('work', 'start', 'end');
const [measure] = performance.getEntriesByName('work');
console.log('Duration:', measure.duration);
// Resource timing
const resources = performance.getEntriesByType('resource');
resources.forEach(r => {
console.log(r.name, r.duration);
});
console.time('operation');
await doSomething();
console.timeEnd('operation');
| Problem | Symptom | Fix |
|---|---|---|
| Jank | Stuttering scroll | Use throttle, optimize DOM |
| Memory leak | Growing memory | Clear refs, remove listeners |
| Long task | UI freeze | Split work, use workers |
| Large bundle | Slow load | Code split, tree shake |
// 1. Profile in DevTools Performance panel
// 2. Check for long tasks (> 50ms)
// 3. Analyze bundle with webpack-bundle-analyzer
// 4. Run Lighthouse audit
// 5. Monitor with web-vitals library
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src;
observer.unobserve(entry.target);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => {
observer.observe(img);
});
// Only render visible items
function renderVisibleItems(scrollTop, containerHeight) {
const startIndex = Math.floor(scrollTop / itemHeight);
const endIndex = startIndex + Math.ceil(containerHeight / itemHeight);
return items.slice(startIndex, endIndex);
}
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.