Performance: Default actions
This concept affects how quickly user interactions respond and how smoothly the page updates after events.
function handleClick(event) { // Let default action happen immediately console.log('Immediate action'); // Run slow code asynchronously without blocking setTimeout(() => { console.log('Delayed action'); }, 1000); } <button on:click={handleClick}>Click me</button>
function handleClick(event) { event.preventDefault(); // heavy computation or slow code here setTimeout(() => { console.log('Delayed action'); }, 1000); } <button on:click={handleClick}>Click me</button>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking default action with heavy JS | Minimal | 0 immediate, delayed reflows possible | Low immediate, higher delayed | [X] Bad |
| Allowing default action, async heavy JS | Minimal | 0 immediate | Low | [OK] Good |
focus to an input element in Svelte?use:actionName on elements.<input use:focus /> uses use:focus, which is the correct way to apply the action.use: prefix to apply default actions [OK]action: or on: instead of use:function highlight(node) {
node.style.backgroundColor = 'yellow';
return {
destroy() {
node.style.backgroundColor = '';
}
};
}
<div use:highlight>Hello</div>backgroundColor to 'yellow' on the node when applied.use:highlight, so its background color becomes yellow on render.function logClick(node) {
node.addEventListener('click', () => console.log('Clicked!'));
}destroy method to remove listeners and avoid memory leaks.autoFocus that focuses an input element when it appears and logs "Focused" once. Which code correctly implements this behavior?node.focus() and logging immediately runs once when the element appears.destroy method is valid and ensures cleanup structure.Pass the test and this pattern moves unknown