0
0
Svelteframework~5 mins

Compiler-based approach (no virtual DOM) in Svelte

Choose your learning style9 modes available
Introduction

This approach turns your code into efficient JavaScript before running it. It skips the extra step of comparing changes in a virtual copy of the page, making updates faster and simpler.

When you want your web app to load and update very quickly.
If you prefer smaller files sent to the browser for faster loading.
When you want less code running in the browser for better battery life on devices.
If you want simpler debugging because the code matches what runs in the browser.
When you want to avoid the complexity of managing a virtual copy of the page.
Syntax
Svelte
No special syntax in your code; the Svelte compiler automatically converts your components into efficient JavaScript that updates the real DOM directly.
Svelte compiles your components at build time, so no virtual DOM is used at runtime.
This means your app updates the real page elements directly, without extra overhead.
Examples
This Svelte component updates the real page directly when you click the button. The compiler creates efficient code to change only the number shown.
Svelte
<script>
  let count = 0;
  function increment() {
    count += 1;
  }
</script>

<button on:click={increment}>
  Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
The compiler turns this into code that updates the heading directly when name changes, without using a virtual DOM.
Svelte
<script>
  let name = 'Friend';
</script>

<h1>Hello {name}!</h1>
Sample Program

This simple Svelte component shows a button with a message. Each click updates the message directly on the page. The compiler creates JavaScript that changes only the text inside the button, without using a virtual DOM.

It also includes an ARIA label for accessibility.

Svelte
<script>
  let message = 'Hello';
  let count = 0;
  function update() {
    count += 1;
    message = `Clicked ${count} times`;
  }
</script>

<button on:click={update} aria-label="Click to update message">
  {message}
</button>
OutputSuccess
Important Notes

Svelte's compiler approach means less code runs in the browser, improving speed and battery life.

Because it updates the real DOM directly, debugging is easier--you see exactly what your code does.

This approach is different from frameworks that keep a virtual copy of the page and compare changes before updating.

Summary

Svelte compiles your code into efficient JavaScript that updates the real page directly.

This avoids the extra step of using a virtual DOM, making apps faster and simpler.

It helps with performance, smaller file sizes, and easier debugging.