Vanilla js ui race conditions

From Project-N-E-K-O/N.E.K.O · View interactive version

Vanilla js ui race conditions is an AI agent skill from the GitHub repository Project-N-E-K-O/N.E.K.O. Dealing with delayed DOM generation, lazy loading, and optimistic state synchronization in vanilla JavaScript without a reactive framework.

How to use this skill

Skill file

应对原生 JS 中的 DOM 竞态与乐观更新陷阱

症状

根本原因

原因 1: 不同模型/模块的 DOM 懒加载时机不一致

原因 2: 乐观 UI (Optimistic UI) 与底层状态的竞态冲突

代码解决方案

1. 应对懒加载 DOM 的绑定轮询(安全可靠)

`javascript

const bindEvents = () => {

// 兼容多个 ID 解析

const getEl = (ids) => {

for (let id of ids) {

const el = document.getElementById(id);

if (el) return el;

}

return null;

};

const targetEl = getEl(['live2d-agent-keyboard', 'vrm-agent-keyboard']);

// 如果没找到,自己建立一个 500ms 后的新宏任务来重试,然后 return 本次任务。

if (!targetEl) {

setTimeout(bindEvents, 500);

return;

}

// 找到了,顺次执行并结束,不会留下任何定时器垃圾

targetEl.addEventListener('change', myLogic);

myLogic(); // 手动触发第一次检查

};

setTimeout(bindEvents, 100); // 发动第一下

`

2. 多源状态判定降级(防止覆盖)

`javascript

const checkState = () => {

const isUiInteractive = domCheckbox && !domCheckbox.disabled;

let isFeatureOn = false;

if (!isUiInteractive) {

// UI 在转圈加载,信任乐观状态或后端缓存

isFeatureOn = optimisticState !== undefined ? optimisticState : backendFlags;

} else {

// UI 处于可用交互态,百分百信任当前 DOM

isFeatureOn = optimisticState !== undefined ? optimisticState : domCheckbox.checked;

}

}

`

关键经验

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.