Skip to content
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 2024-06-20 - Unnecessary initial DOM updates for default language
**Learning:** The simple static i18n implementation runs `node.textContent = dict[node.dataset.i18n]` for every translatable node on the initial script load, even when the HTML is already written in the target language (Korean). This creates unnecessary layout/paint operations and blocking time on the main thread for elements that don't need text changes.
**Action:** Always check if the current value matches the desired value before updating the DOM (`node.textContent !== newText`), and add early exits when setting state to the same value to avoid redundant DOM traversal and writes.
## 2024-06-27 - 초기 언어 로드 시 불필요한 DOM 탐색 제거
**Learning:** 초기 로드 시 요청된 언어가 HTML의 기본 언어(ko)와 동일한 경우, 모든 DOM 텍스트 노드를 탐색하고 치환하는 불필요한 작업을 생략하면 성능이 향상됨을 확인했습니다.
**Action:** `isInitialDefault` 조건을 추가하여 초기 로드 시 불필요한 DOM 순회 코드가 실행되지 않도록 개선했습니다.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# CHANGELOG

## [Unreleased]
- **성능 개선**: `i18n.js`에서 초기 로드 시 기본 언어가 한국어(ko)인 경우 불필요한 DOM 순회 및 텍스트 업데이트를 생략하도록 개선했습니다.
- **테스트 추가**: 다국어 처리 로직의 무결성을 검증하기 위해 `test_i18n.html` 테스트 파일을 추가했습니다.
24 changes: 16 additions & 8 deletions i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -315,8 +315,7 @@ function setLanguage(lang) {

const dict = messages[lang] || messages.ko;

if (!i18nNodes) {
i18nNodes = document.querySelectorAll("[data-i18n]");
if (!langButtons) {
langButtons = document.querySelectorAll("[data-lang]");
metaDesc = document.querySelector('meta[name="description"]');
ogDesc = document.querySelector('meta[property="og:description"]');
Expand Down Expand Up @@ -346,13 +345,22 @@ function setLanguage(lang) {
}
}

// Only update textContent if it actually changed to avoid layout recalculations
i18nNodes.forEach((node) => {
const newText = dict[node.dataset.i18n];
if (newText && node.textContent !== newText) {
node.textContent = newText;
// ⚡ Bolt: 기본 언어로 초기 로드 시 불필요한 DOM 텍스트 읽기 및 탐색 생략 (성능 개선)
const isInitialDefault = lang === "ko" && !i18nNodes;

if (!isInitialDefault) {
if (!i18nNodes) {
i18nNodes = document.querySelectorAll("[data-i18n]");
}
});

// Only update textContent if it actually changed to avoid layout recalculations
i18nNodes.forEach((node) => {
const newText = dict[node.dataset.i18n];
Comment thread
seonghobae marked this conversation as resolved.
if (newText && node.textContent !== newText) {
node.textContent = newText;
}
});
}

langButtons.forEach((button) => {
const pressed = String(button.dataset.lang === lang);
Expand Down
63 changes: 63 additions & 0 deletions test_i18n.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>i18n Test</title>
<meta name="description" content="test">
<meta property="og:description" content="test">
</head>
<body>
<div data-i18n="hero.title">맥락지혜 연구실</div>
<button type="button" data-lang="ko" aria-pressed="true">KO</button>
<button type="button" data-lang="en" aria-pressed="false">EN</button>
<img id="footer-logo" src="assets/context-wisdom-lab-logo.svg" alt="맥락지혜 연구실 · Contextual Wisdom Lab">
<script>
// Mock for global storage and initial test state
window.localStorageMock = {
getItem: function() { return null; },
setItem: function() {}
};
Object.defineProperty(window, 'localStorage', { value: window.localStorageMock });
</script>
<script src="i18n.js"></script>
<script>
// Simple test harness
let testsPassed = 0;
let testsTotal = 0;

function assertEqual(actual, expected, testName) {
testsTotal++;
if (actual === expected) {
testsPassed++;
console.log(`[PASS] ${testName}`);
} else {
console.error(`[FAIL] ${testName} - Expected '${expected}', got '${actual}'`);
}
}

requestAnimationFrame(() => {
console.log("Running tests...");

assertEqual(currentLang, "ko", "Initial language should be 'ko'");

// Test 2: Switch to EN updates nodes correctly
setLanguage("en");
assertEqual(currentLang, "en", "Language should be 'en' after setting");
const titleNode = document.querySelector('[data-i18n="hero.title"]');
assertEqual(titleNode.textContent, "Contextual Wisdom Lab", "Title text should change to English");

// Test 3: Switch back to KO updates nodes correctly
setLanguage("ko");
assertEqual(currentLang, "ko", "Language should be 'ko' after setting back");
assertEqual(titleNode.textContent, "맥락지혜 연구실", "Title text back to Korean");

console.log(`Test Summary: ${testsPassed}/${testsTotal} passed.`);

if (testsPassed === testsTotal) {
// Output special string for script to catch
console.log("ALL_TESTS_PASSED_SUCCESSFULLY");
}
});
</script>
</body>
</html>