К основному содержанию
скилл CX Codex

optimize-web-animations — скилл для Claude Code: что делает

Останавливает фоновую анимацию вне экрана и устраняет утечки памяти во фронтенде. Пригодится, когда страница с CSS, Canvas или WebGL нагружает процессор и тормозит скролл.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add MengTo/Skills --skill optimize-web-animations -a claude-code
Открыть на GitHub

Что делает optimize-web-animations

Скилл находит тяжёлые CSS-анимации, бесконечные циклы requestAnimationFrame и эффекты на Three.js или GSAP. Сначала он замеряет страницу в Codex Browser. Браузер Chrome скилл не открывает без прямой просьбы. Профайлер считает работающие анимации в шапке, середине страницы и подвале, чтобы выявить лишнюю нагрузку вне экрана.

Для оптимизации скилл вешает IntersectionObserver и переключает класс is-offscreen. Правило animation-play-state: paused !important замораживает скрытые CSS-эффекты и псевдоэлементы. Циклы в Canvas или WebGL останавливаются при уходе из видимости и возобновляются при скролле. Очистка эффектов в React освобождает таймеры, слушатели событий, текстуры и геометрии Three.js. Если не останавливать WebGL-рендеры вне экрана, они продолжают греть видеокарту впустую.

После правок скилл повторно замеряет поведение и проверяет, что показатель offscreenRunningCount равен 0. Он запускает npm run lint и сборку проекта. Если в репозитории остались чужие незакоммиченные файлы, скилл использует временный индекс Git для точечного коммита.

Какие задачи решает

  • Остановить невидимые CSS-анимации и циклы requestAnimationFrame при скролле
  • Устранить утечки памяти от таймеров, слушателей событий и подписок в React
  • Освободить ресурсы WebGL, текстуры Three.js и геометрии при размонтировании компонентов
  • Зафиксировать базовое число работающих анимаций через Codex Browser

Примеры запросов агенту

  • Оптимизируй анимации на главной странице через optimize-web-animations и останови всё, что крутится вне экрана.
  • Проверь утечки памяти и зависания Canvas при переходах между маршрутами.
  • Уменьши нагрузку на видеокарту от WebGL-эффектов и бегущей строки в проекте.

Как установить optimize-web-animations

1Через Skills CLI (Vercel)

npx skills add MengTo/Skills --skill optimize-web-animations -a claude-code

2Вручную: положить файлы

~/.claude/skills/optimize-web-animations/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/optimize-web-animations/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора148

gsap Скилл для ИИ-агента, который помогает писать и отлаживать веб-анимации на GSAP: таймлайны, ScrollTrigger, stagger, трансформации. CX Codex +1 1 800установок design-first-ui-prompting Превращает сырые идеи интерфейсов в строгие спецификации для генерации UI. Помогает фиксировать сетку, типографику и отступы по правилам дизайн-систем. CX Codex +1 1 800установок gsap-scrolltrigger-storytelling Скилл для скролл-сторителлинга: закреплённые секции, послойное появление интерфейса и переходы между сценами на GSAP ScrollTrigger. CX Codex +1 1 800установок tailwindcss Скилл для ИИ-агента, который помогает верстать интерфейсы на Tailwind CSS: сетки, типографика, адаптив, темы и паттерны компонентов. CX Codex +1 1 700установок progressive-blur Скилл создаёт верхний или нижний градиентный blur в CSS через слои backdrop-filter. Пригодится для мягкого затемнения края экрана. CX Codex +1 1 700установок cobejs Скилл помогает агенту собрать лёгкий вращающийся глобус с метками на cobe, без полного three.js. Пригодится для hero-блока или страницы «о нас». CX Codex +1 1 700установок webgl-3d-object Добавляет в агент правила генерации трёхмерных объектов на Three.js с честным PBR-освещением, тенями и анимацией вместо псевдо-3D на CSS. CX Codex +1 1 600установок video-to-superprompt Разбирает референсное видео и готовит подробный промпт для воссоздания интерфейса, анимаций и прокрутки. Пригодится перед сборкой страницы или приложения по видеодемо. CX Codex +1 1 600установок

Похожие

review-animations emilkowalski Проверяет код интерфейсных анимаций по принципам Эмиля Ковальски. Помогает убрать дерганые переходы, медленный ease-in и лишнюю нагрузку на процессор. CX Codex +1 256 500установок improve-animations emilkowalski Скилл проводит ревизию анимаций в кодовой базе и составляет готовые планы доработок. Помогает найти неудачные тайминги и прыгающие элементы, не меняя код напрямую. CX Codex +1 224 200установок web-game-foundations официальный OpenAI Задаёт архитектуру браузерной игры до начала кодинга. Помогает выбрать движок и отделить симуляцию от рендера. CX Codex GP ChatGPT 52установок mapbox-web-performance-patterns mapbox Скилл учит ИИ-агента оптимизировать приложения на Mapbox GL JS: убирать каскадные задержки данных, уменьшать бандл стилей и переводить маркеры на GPU-слои. CX Codex +1 2 500установок scroll-animations dylantarre Скилл для анимаций, привязанных к прокрутке: появления блоков, параллакс, липкие шапки, индикаторы прогресса. Пригодится, когда страница должна реагировать на скролл, а не просто листаться. CX Codex +1 1 100установок exit-animations dylantarre Скилл подсказывает агенту, как анимировать исчезновение элементов: закрытие модалок, скрытие уведомлений, удаление строк списка. CX Codex +1 500установок

Рядом в теме «Фронтенд и UI»

Всё по теме «Фронтенд и UI» →

Вопросы о optimize-web-animations

Как установить optimize-web-animations в Claude Code?

Выполните команду npx skills add MengTo/Skills --skill optimize-web-animations -a claude-code.

Что делает этот скилл?

Он находит активные анимации вне экрана, ставит их на паузу через IntersectionObserver и очищает ресурсы WebGL или таймеров при уходе со страницы.

Какой браузер использует скилл для замеров?

Скилл проводит тесты в Codex Browser и не запускает Google Chrome, если вы прямо об этом не попросите.

Исходный текст

SKILL.md · MIT
---
name: optimize-web-animations
description: Profile, audit, and optimize frontend page performance with emphasis on animation work, memory-leak risks, long-session slowdowns, CSS animations, canvas/WebGL requestAnimationFrame loops, marquees, skeletons, GSAP/Three/Matter effects, timers, listeners, and observers. Use when the user asks to make animations performant, pause offscreen animations, look for memory leaks, profile pages that slow the computer over time, fix janky scrolling, reduce CPU/GPU use, or repeat the "only play in view" optimization on React/Vite/Next/frontend pages using Codex Browser.
---

# Optimize Web Animations

## Core Rule

Measure the real page before editing. The goal is not to remove motion; it is to make offscreen work stop, visible motion resume correctly, and route/unmount cleanup release long-lived resources.

Use Codex Browser when available, especially for localhost pages. Do not use Chrome unless the user explicitly asks for it.

## Workflow

1. Inspect repo context.
   - Read `AGENTS.md` or local instructions.
   - Run `git status --short` early.
   - Find page components, animation hooks, CSS keyframes, `requestAnimationFrame`, `setInterval`, `setTimeout`, canvas/WebGL/physics components, media elements, GSAP timelines/tweens, and existing visibility utilities.
   - Search effect cleanup for event listeners, observers, RAF loops, intervals, timers, external scripts, media streams, WebGL textures/materials/geometries/renderers, and async work that can complete after unmount.
   - If the worktree is dirty, plan narrow staging from the start.

2. Capture a baseline in the browser.
   - Open the exact route the user named.
   - Profile at top, mid-page, footer/lower content, and one mobile viewport when layout could differ.
   - Count CSS animations by computed `animationName`, `animationPlayState`, and visibility. Include `::before` and `::after`.
   - Inspect canvases/WebGL elements separately; CSS profiling does not prove RAF loops have stopped.
   - Record which animation names are running offscreen and the DOM owners responsible.
   - For memory/leak asks, also record element/canvas/image/iframe counts, exposed JS heap metrics when available, an idle sample after 10-30 seconds, and a short route-cycle sample. If heap APIs return `null` or the Browser sandbox blocks monkey-patching, say so and rely on stable observable counts plus source audit.
   - Keep stress tests bounded. A Browser tab crash during profiling is evidence of overload, but do not over-attribute the cause unless reproduced by a minimal test.
   - See `references/browser-profiling.md` for a reusable Codex Browser evaluator.

3. Patch the smallest owner that controls the motion.
   - Prefer an existing page reveal/visibility hook if the app has one.
   - Otherwise add an `IntersectionObserver` that toggles a stable class such as `is-offscreen` on sections and animated child elements.
   - Pause CSS animations with targeted rules:

```css
main > section.is-offscreen .expensive-animation,
.expensive-animation.is-offscreen {
  animation-play-state: paused !important;
}
```

   - For repeated cards or placeholders, observe the card shell and the animated descendants, not the whole document.
   - For marquee/ticker tracks, pause the track when its section is offscreen.
   - For skeleton loaders and pseudo-element glimmers, include `::before` and `::after` pause selectors where needed.
   - For canvas/WebGL/physics loops, gate the RAF loop directly:
     - Start when the canvas/container intersects.
     - Cancel `requestAnimationFrame` when offscreen.
     - Resume on re-entry.
     - Disconnect observers and cancel frames on cleanup.
     - Add a non-visual debug marker such as `data-animation-active` when it helps browser verification.
   - Respect `prefers-reduced-motion` if the component already does, and avoid introducing React render loops for scroll/animation state.
   - For leak hardening:
     - Clear every timeout/interval created by the effect.
     - Cancel RAF before unmount and before restarting a loop.
     - Disconnect `IntersectionObserver`, `ResizeObserver`, `MutationObserver`, and custom subscriptions.
     - Remove global/window/document listeners with the same handler reference.
     - Dispose Three/WebGL textures, materials, geometries, renderers, and remove renderer DOM nodes.
     - Kill GSAP tweens/timelines for DOM nodes and mutable objects such as shader uniforms.
     - Stop media streams and pause detached video/audio sources.
     - Guard async loaders with an `isDisposed` flag and dispose loaded resources if they resolve after unmount.
     - In React cleanup, capture `ref.current` values inside the effect before returning cleanup if lint warns the ref may change.
     - Cap physics or simulation frame deltas after visibility pauses so delayed frames do not run oversized updates.

4. Verify behavior, not just builds.
   - Reload the route and rerun the same top/mid/footer/mobile profiles.
   - Target result: `offscreenRunningCount: 0` for the page sections under test.
   - Confirm visible animations still run or resume when scrolled into view.
   - Confirm RAF/canvas loops report inactive offscreen and active in view, or otherwise prove cancellation from source/runtime state.
   - For leak audits, compare before/after route cycles and idle samples. DOM/canvas/image counts should return to the same baseline after repeated navigation, allowing for small expected async content changes.
   - Exercise a normal page interaction such as search/filter/navigation so the observer does not break dynamic content.
   - Check fresh-tab console warnings/errors.

5. Run local checks.
   - Use the repo's normal gates. For React/Vite apps this is often:

```bash
git diff --check
npm run lint
npm run build
```

   - Mention known non-fatal warnings separately from failures.

6. Commit narrowly when requested by repo/user instructions.
   - If unrelated dirty changes exist, use an isolated index:

```bash
rm -f /tmp/<task>-index
GIT_INDEX_FILE=/tmp/<task>-index git read-tree HEAD
# Apply only the intended hunks to the temporary index.
GIT_INDEX_FILE=/tmp/<task>-index git diff --cached --check
GIT_INDEX_FILE=/tmp/<task>-index git commit -m "Pause offscreen <page> animations"
git restore --staged <files> 2>/dev/null || true
```

   - Never stage broad files from a dirty worktree unless every hunk belongs to the task.

7. Report with evidence.
   - Lead with findings: what was still running, what looked leak-prone, and what could not be measured.
   - Separate source-audit risks from live Browser measurements.
   - Include the exact sampled route(s), offscreen animation counts, DOM/canvas count stability, route-cycle result, and local checks.
   - State limitations plainly, especially unavailable heap counters or blocked Browser instrumentation.

## Good Fix Patterns

- Section-level `is-offscreen` plus element-level `is-offscreen` for long sections where below-the-fold child animations can still run.
- Shared visibility selector constants per route, such as `COURSES_PAGE_ANIMATION_VISIBILITY_SELECTOR`.
- `IntersectionObserver` thresholds around `0.01` for animation gating.
- Direct RAF loop control for WebGL/canvas effects; CSS `animation-play-state` cannot pause JavaScript render loops.
- Frame delta caps for physics loops that resume after a paused or delayed frame.
- Captured cleanup nodes for React refs used by GSAP/WebGL effects.
- `isDisposed` guards for image/video/texture/data loaders that may resolve after unmount.
- Short idle and route-cycle probes to catch accumulating DOM nodes, canvases, iframes, or unreleased media.

## Avoid

- Removing all animations to make the profile pass.
- Pausing visible hero motion because an ancestor selector is too broad.
- Assuming `animation-play-state` covers pseudo-elements or JavaScript RAF loops.
- Trusting a single top-of-page measurement on long pages.
- Treating unavailable heap counters as proof there is no memory leak.
- Running unbounded stress loops in the Browser; use bounded cycles and record crashes without overstating causality.
- Using screenshots alone as performance proof.
- Letting unrelated local hunks ride along in the commit.

© MengTo · MIT · MengTo/Skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой