f8b21af4be
10_Wiki/Topics 대규모 정리: - 오류 캡처/미완성 stub 문서 227개 제거 - 교차폴더 중복 43클러스터 병합 (63파일 → redirect) - 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건 - 카테고리 MOC 6개 신규 생성 - Graph 섹션 미해결 related-keyword 링크 10,058건 제거 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
176 lines
5.3 KiB
Markdown
176 lines
5.3 KiB
Markdown
---
|
|
id: wiki-2026-0508-long-tasks
|
|
title: Long Tasks API
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [Long Tasks, Long Animation Frame, LoAF, Main Thread Blocking]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.9
|
|
verification_status: applied
|
|
tags: [web-perf, performance-api, inp, main-thread, browser]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack: { language: JavaScript, framework: PerformanceObserver }
|
|
---
|
|
|
|
# Long Tasks API
|
|
|
|
## 매 한 줄
|
|
> **"매 long task = main thread 50ms+ 블록"**. INP/Responsiveness의 직접 원인. PerformanceObserver로 측정·attribute한다.
|
|
|
|
## 매 핵심
|
|
### 매 정의
|
|
- **Long Task**: 단일 task가 50ms 초과로 main thread 점유.
|
|
- 사용자 입력·rendering 지연 → INP 악화.
|
|
- W3C spec: `longtask` PerformanceEntry.
|
|
|
|
### 매 후속 표준 (LoAF)
|
|
- **Long Animation Frame** (Long Animation Frames API): frame 단위, attribution 강화.
|
|
- entryType `long-animation-frame` — script source, style/layout 시간 포함.
|
|
- Long Tasks API보다 정확하고 디버깅 친화적 (2024+).
|
|
|
|
### 매 측정 항목
|
|
- `duration`, `startTime`
|
|
- `attribution` (Long Tasks): TaskAttributionTiming, container 정도만 (cross-origin 익명화)
|
|
- `scripts[]` (LoAF): name, sourceURL, function, invoker, executionStart/forcedStyleAndLayoutDuration
|
|
|
|
### 매 흔한 원인
|
|
1. 큰 JS 번들 parse/compile
|
|
2. 동기 layout/style (forced reflow)
|
|
3. 무거운 React render (큰 리스트, memo 부재)
|
|
4. JSON parse 큰 payload
|
|
5. 동기 third-party script
|
|
6. Hydration burst (Next.js, Nuxt)
|
|
|
|
### 매 완화
|
|
- Code split, dynamic import
|
|
- `requestIdleCallback`, `scheduler.postTask`, `scheduler.yield()`
|
|
- Web Worker로 오프로드
|
|
- Virtualization (큰 리스트)
|
|
- React: Suspense, useDeferredValue, transitions
|
|
- Defer non-critical scripts, async chunks
|
|
|
|
## 💻 패턴
|
|
### Long Tasks 관찰
|
|
```js
|
|
const obs = new PerformanceObserver((list) => {
|
|
for (const entry of list.getEntries()) {
|
|
console.log("long task", entry.duration, entry.name, entry.attribution);
|
|
}
|
|
});
|
|
obs.observe({ type: "longtask", buffered: true });
|
|
```
|
|
|
|
### Long Animation Frame (현대)
|
|
```js
|
|
const obs = new PerformanceObserver((list) => {
|
|
for (const e of list.getEntries()) {
|
|
if (e.duration < 50) continue;
|
|
for (const s of e.scripts) {
|
|
console.log("LoAF script", s.name, s.sourceURL,
|
|
s.duration, "fwd-layout:", s.forcedStyleAndLayoutDuration);
|
|
}
|
|
}
|
|
});
|
|
obs.observe({ type: "long-animation-frame", buffered: true });
|
|
```
|
|
|
|
### scheduler.yield (cooperative)
|
|
```js
|
|
async function processItems(items) {
|
|
for (const item of items) {
|
|
doWork(item);
|
|
if (navigator.scheduling?.isInputPending?.() || performance.now() - last > 5) {
|
|
await scheduler.yield(); // chunk 양보
|
|
last = performance.now();
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
### requestIdleCallback fallback
|
|
```js
|
|
function chunked(items, fn) {
|
|
let i = 0;
|
|
function run(deadline) {
|
|
while (i < items.length && deadline.timeRemaining() > 0) fn(items[i++]);
|
|
if (i < items.length) requestIdleCallback(run);
|
|
}
|
|
requestIdleCallback(run);
|
|
}
|
|
```
|
|
|
|
### Web Worker로 오프로드
|
|
```js
|
|
// main
|
|
const w = new Worker("./parse.worker.js", { type: "module" });
|
|
w.postMessage(largePayload);
|
|
w.onmessage = (e) => render(e.data);
|
|
|
|
// parse.worker.js
|
|
self.onmessage = (e) => {
|
|
const result = heavyParse(e.data);
|
|
self.postMessage(result);
|
|
};
|
|
```
|
|
|
|
### React deferred / transition
|
|
```jsx
|
|
import { useDeferredValue, useTransition } from "react";
|
|
const deferred = useDeferredValue(query);
|
|
const [isPending, start] = useTransition();
|
|
start(() => setFilter(next)); // non-urgent → no long task on type
|
|
```
|
|
|
|
### web-vitals 통합
|
|
```js
|
|
import { onINP } from "web-vitals/attribution";
|
|
onINP((m) => {
|
|
// m.attribution.longAnimationFrameEntries → 원인 frame
|
|
beacon("inp", m);
|
|
}, { reportAllChanges: true });
|
|
```
|
|
|
|
## 매 결정 기준
|
|
| 상황 | 도구 |
|
|
|---|---|
|
|
| 측정 시작 | LoAF (지원) → Long Tasks fallback |
|
|
| 사용자 INP 추적 | web-vitals attribution |
|
|
| CPU-bound | Web Worker |
|
|
| 큰 리스트 처리 | scheduler.yield, chunking |
|
|
| Render bottleneck | useDeferredValue, virtualization |
|
|
| Third-party 무거움 | defer/async, Partytown |
|
|
|
|
**기본값**: web-vitals onINP + LoAF observer로 attribute → 가장 큰 script 우선 최적화.
|
|
|
|
## 🔗 Graph
|
|
- 부모: [[Web-Performance]]
|
|
- 변형: [[Long-Animation-Frame]]
|
|
- 응용: [[INP]], [[Core Web Vitals Optimization (INP, LCP 개선)|Core-Web-Vitals]]
|
|
- Adjacent: [[Web Worker (웹 워커)|Web-Workers]], [[Scheduler-API]], [[Code-Splitting]]
|
|
|
|
## 🤖 LLM 활용
|
|
**언제**: PerformanceObserver 코드, 원인 분류, 완화 전략 매핑.
|
|
**언제 X**: 실제 attribution은 production trace로 검증해야 정확.
|
|
|
|
## ❌ 안티패턴
|
|
- 50ms threshold만 보고 47ms task 무시 (LoAF가 누적 표시)
|
|
- requestAnimationFrame 안에 무거운 sync 작업
|
|
- Worker로 보내고 직렬화 cost > 작업 cost
|
|
- setTimeout(fn, 0)으로 yield (실제 양보 부족) → scheduler.yield
|
|
- Long task 발생만 알리고 attribution 안 봄 → 원인 파악 불가
|
|
- DevTools만 보고 production 측정 누락
|
|
|
|
## 🧪 검증 / 중복
|
|
- Verified (W3C Long Tasks, web.dev INP, Long Animation Frames API). 신뢰도 A.
|
|
- 중복: 없음.
|
|
|
|
## 🕓 Changelog
|
|
| 날짜 | 변경 |
|
|
|---|---|
|
|
| 2026-05-08 | Phase 1 |
|
|
| 2026-05-10 | Manual cleanup — LoAF, scheduler.yield, web-vitals 통합 |
|