> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Main-thread scripts

A **main-thread script** restyles an element on every touch or scroll event without running Angular's change detection. Use one for drags, scroll-linked effects and other work that must keep up with a finger. It's a function that runs on the [main thread](/guide/glossary.md#main-thread) with a direct handle to the native element (see [Glossary](/guide/glossary.md#main-thread-script)).


## What they add

Your template event handlers, such as `(bindtap)`, already run on the main thread, inside the native event (see [Threads](/guide/concepts/threads.md)). So a main-thread script doesn't save a trip between threads. It gives you four other things:

- **No change detection per event.** A `(bindtouchmove)` handler marks its component for checking, so Angular runs change detection after every move. A main-thread script changes the element itself, and Angular does no work.
- **An element handle.** In a main-thread script, `event.currentTarget` and `event.target` are `MainThread.Element` objects with `setStyleProperty()`, `setAttribute()`, `querySelector()`, `animate()` and `invoke()`. In a template handler, `$event.currentTarget` is plain data.
- **Results from element methods.** `invoke()` calls a [UI method](/guide/glossary.md#ui-method) and returns a Promise of its result, such as the element's size and position.
- **A way to the background thread.** `runOnBackground()` calls a function on the [background thread](/guide/glossary.md#background-thread), which has APIs the main thread lacks.

## Bind a script to an event

```typescript title="src/app/app.ts"
import { Component } from '@angular/core';
import {
  LYNX_ELEMENTS,
  LynxMainThreadEvent,
  mainThreadFn,
  type MainThread,
} from '@blotch/angular-lynx';

// Fades the card as the finger moves right, on every touchmove.
const fade = mainThreadFn((event: MainThread.TouchEvent) => {
  const touch = event.touches[0];
  if (!touch) return;
  const opacity = Math.max(0.3, Math.min(1, touch.clientX / 300));
  event.currentTarget.setStyleProperty('opacity', String(opacity));
});

const reset = mainThreadFn((event: MainThread.TouchEvent) => {
  event.currentTarget.setStyleProperty('opacity', '1');
});

@Component({
  selector: 'app-root',
  imports: [LYNX_ELEMENTS, LynxMainThreadEvent],
  template: `
    <view
      [mainThreadBindtouchmove]="fade"
      [mainThreadBindtouchend]="reset"
      style="height: 120px; background-color: #3b82f6;"
    >
      <text style="color: white;">Drag across me</text>
    </view>
  `,
})
export class App {
  readonly fade = fade;
  readonly reset = reset;
}
```

- **`mainThreadFn()`** registers the function on the main thread and returns a handle.
- **`LynxMainThreadEvent`** provides the `mainThreadBind*` and `mainThreadCatch*` inputs. Bind them with square brackets: you pass the handle in, you don't listen with `( )`.
- **`catch` instead of `bind`** stops the event bubbling, as with template events (see [Handling taps and events](/guide/elements/event-handling.md)).
- **Style changes are batched.** AngularLynx draws them once, after your function returns. Property names are kebab-case and values are strings.

The inputs cover `tap`, `touchstart`, `touchmove`, `touchend`, `mousedown`, `mousemove`, `mouseup`, `longpress` and `scroll`. `animationstart`, `animationend`, `transitionend` and `layoutchange` have a `bind` form only. The [`LynxMainThreadEvent` reference](/api/main-thread/main-thread-event.md) lists them all.

A desktop browser fires mouse events, not touch events. To drag in the [web preview](/guide/glossary.md#web-preview), bind `mainThreadBindmousemove` as well. Phones never fire it, so binding both is safe.

## Use the `'main thread'` directive

Instead of calling `mainThreadFn()`, make `'main thread'` the first statement of the function:

```typescript
import type { MainThread } from '@blotch/angular-lynx';

const reset = (event: MainThread.TouchEvent) => {
  'main thread';
  event.currentTarget.setStyleProperty('opacity', '1');
};
```

The build wraps the function in `mainThreadFn()` and adds the import. Both forms behave the same.

- **Arrow functions and function expressions** with a block body are wrapped. `'main-thread'` works too.
- **Function declarations and class methods** aren't. Write `const name = () => { 'main thread'; … }` instead.

## Define scripts at module level

Put main-thread scripts at the top level of a file, as above. A script is registered once, when its file loads.

A class property, such as `readonly fade = (event) => { 'main thread'; … }`, works for a `[mainThreadBind*]` input and can read `this`. Each instance registers its own function, which is released when the component or service is destroyed.

A script runs on the main thread, like the rest of your app, so it reads the same module-level variables as your components. Data from the background thread reaches it only as copied JSON.

## Keep state between events

A **`MainThreadRef`** holds a value that your scripts keep between events, such as where a drag started:

```typescript
import {
  createMainThreadRef,
  mainThreadFn,
  type MainThread,
} from '@blotch/angular-lynx';

const startX = createMainThreadRef(0);

const dragStart = mainThreadFn((event: MainThread.TouchEvent) => {
  startX.current = event.touches[0]?.clientX ?? 0;
});

const dragMove = mainThreadFn((event: MainThread.TouchEvent) => {
  const dx = (event.touches[0]?.clientX ?? 0) - startX.current;
  event.currentTarget.setStyleProperty('transform', `translateX(${dx}px)`);
});
```

- **On the main thread, a ref works like a module-level variable** that's labeled as script state.
- **The background thread has a copy of its own.** It also loads each file that creates a ref at module level. The two copies aren't synced.
- **Pass a ref to a background function,** and it arrives as the background thread's copy.

## Call the background thread

`runOnBackground()` runs a **`backgroundFn()`** on the background thread and returns a Promise of its result:

```typescript
import {
  backgroundFn,
  mainThreadFn,
  type MainThread,
} from '@blotch/angular-lynx';

// Runs on the background thread, which has APIs such as
// lynx.createSelectorQuery() that the main thread doesn't.
const describe = backgroundFn((label: string) => `${label} (background)`);

const onTap = mainThreadFn((event: MainThread.TouchEvent) => {
  runOnBackground(describe, 'tapped').then((text) => console.log(text));
});
```

- **`runOnBackground()` is a global.** Call it from any of your Angular code, a main-thread script or a template handler: they all run on the main thread.
- **Define `backgroundFn()` at module level.** The background thread loads only the files that define one there, and their imports. It never loads your components, so a function created in a class or a function never registers. The rest of that file's top-level code runs on both threads, unless you [shrink the background thread's script](#shrink-the-background-threads-script). Files that load lazily, such as a lazy route's, work too: the background thread loads them at startup.
- **Arguments and the return value are copied as JSON.**
- **The function can be `async`.** `runOnBackground()` waits for a returned Promise, so the function can `fetch()` data (see [Network requests](/guide/concepts/javascript-environment.md#network-requests)). If it throws or rejects, the Promise `runOnBackground()` returned rejects with the same message.

[Call element methods](/guide/selector-query.md) uses this to reach `lynx.createSelectorQuery()`.

## Call a script from your code

`LynxMainThread.runOnMainThread(handle, ...args)` calls a main-thread script and returns a Promise of its result:

```typescript
import { Component, inject } from '@angular/core';
import {
  LYNX_ELEMENTS,
  LynxMainThread,
  mainThreadFn,
} from '@blotch/angular-lynx';

const double = mainThreadFn((n: number) => n * 2);

@Component({
  selector: 'app-double',
  imports: [LYNX_ELEMENTS],
  template: `<view (bindtap)="run()"><text>Double 21</text></view>`,
})
export class Double {
  readonly #mainThread = inject(LynxMainThread);

  run(): void {
    this.#mainThread.runOnMainThread(double, 21).then((n) => console.log(n));
  }
}
```

- **The script runs right away.** Your Angular code is already on the main thread, so the call doesn't cross threads, and the arguments aren't copied.
- **Call it from anywhere in your app,** including a constructor, `ngOnInit` or `effect()`. It runs once per call.

To get from the main thread to the background thread, use `runOnBackground()`, not `runOnMainThread()`.

:::warning Angular doesn't see these changes
A main-thread script changes native elements behind Angular's back.

- A later binding update to the same property, such as `[style.opacity]`, overwrites your change.
- When an element is removed and shown again, by an `@if` or by leaving and returning to a route, AngularLynx rebuilds it from Angular's state. Your changes are gone.

Use scripts for visual effects that follow a gesture. Keep anything that must last in signals.
:::

## Shrink the background thread's script

The background thread runs every top-level statement of the files it loads. Those are the files that define a `backgroundFn()` or a `MainThreadRef` at module level, and the files they import.

So it also computes module-level values that only your components or main-thread scripts read, such as:

- a `signal()` next to a `backgroundFn()`, which keeps Angular's signals in the background thread's script
- a table of icons

Its engine parses and keeps all of that at every launch.

Set the `backgroundTreeShaking` build option to `"aggressive"` to drop the values nothing on the background thread reads:

```json title="angular.json"
"build": {
  "builder": "@blotch/angular-lynx-build:application",
  "options": {
    "backgroundTreeShaking": "aggressive"
  }
}
```

The kitchen-sink example's background script goes from 101 KB to 56 KB. The main thread's script doesn't change, and neither do your background functions, refs and the values they read.

The cost: a top-level declaration whose value nothing on the background thread reads no longer runs there, even when its initializer does something on purpose. This one stops subscribing:

```typescript
// Nothing reads `subscription`, so with "aggressive" the background thread
// never calls addListener().
const subscription = lynx
  .getJSModule('GlobalEventEmitter')
  .addListener('networkChanged', onNetworkChanged);
```

Statements that aren't declarations still run, such as a bare `emitter.addListener(…)` call. So does all of AngularLynx's and other packages' code: only your app's own files are trimmed. Keep work like this out of declarations, or leave the option at its default, `"safe"`.

## Limitations

- **No dependency injection.** A module-level script has no injection context, so `inject()` doesn't work in it.
- **Measuring is asynchronous.** `await element.getBoundingClientRect()` resolves with the element's position and size. A script can't read layout synchronously in Lynx, so measure once, on `touchstart` for example, and keep the result in a `MainThreadRef` for the `touchmove` events that follow.

## Related

- [`mainThreadFn`](/api/main-thread/main-thread-fn.md) and [`LynxMainThreadEvent`](/api/main-thread/main-thread-event.md)
- [`MainThreadRef`](/api/main-thread/main-thread-ref.md), [`LynxMainThread`](/api/main-thread/main-thread-service.md) and [`backgroundFn`](/api/main-thread/background-fn.md)
- [Threads: where your code runs](/guide/concepts/threads.md)
- [Gestures](/guide/gestures/index.md), for pan, pinch and other gesture recognizers
- [Main-thread example](/examples/main-thread.md)
