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 with a direct handle to the native element (see Glossary).
What they add
Your template event handlers, such as (bindtap), already run on the main thread, inside the native event (see Threads). 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.currentTargetandevent.targetareMainThread.Elementobjects withsetStyleProperty(),setAttribute(),querySelector(),animate()andinvoke(). In a template handler,$event.currentTargetis plain data. - Results from element methods.
invoke()calls a 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, which has APIs the main thread lacks.
Bind a script to an event
mainThreadFn()registers the function on the main thread and returns a handle.LynxMainThreadEventprovides themainThreadBind*andmainThreadCatch*inputs. Bind them with square brackets: you pass the handle in, you don't listen with( ).catchinstead ofbindstops the event bubbling, as with template events (see Handling taps and events).- 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 lists them all.
A desktop browser fires mouse events, not touch events. To drag in the 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:
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:
- 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:
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. 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 canfetch()data (see Network requests). If it throws or rejects, the PromiserunOnBackground()returned rejects with the same message.
Call element methods 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:
- 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,
ngOnInitoreffect(). It runs once per call.
To get from the main thread to the background thread, use runOnBackground(), not runOnMainThread().
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
@ifor 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 abackgroundFn(), 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:
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:
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, ontouchstartfor example, and keep the result in aMainThreadReffor thetouchmoveevents that follow.
Related
mainThreadFnandLynxMainThreadEventMainThreadRef,LynxMainThreadandbackgroundFn- Threads: where your code runs
- Gestures, for pan, pinch and other gesture recognizers
- Main-thread example
