FRONTMANFRONTMAN
  • 태그
  • 방명록
  • 글쓰기
  • 관리자
  • HOME
  • 태그
  • 방명록
MutationObserver란?
hahekaku
MutationObserver란?FE/WEB2025. 2. 1. 14:11@hahekaku
Table of Contents

MutationObserver란?

MutationObserver는 DOM(Document Object Model) 요소의 변화(변경 사항)를 비동기적으로 감지할 수 있는 기능을 제공합니다. 예를 들어, 웹 페이지에서 특정 요소의 속성, 자식 노드, 텍스트 콘텐츠가 변경될 때 이를 실시간으로 감지하고 대응할 수 있게 해주는 도구입니다.

MutationObserver는 이전에 사용되던 Mutation Events의 한계를 보완하기 위해 도입된 API입니다. Mutation Events는 성능이 저하되는 문제가 있었지만, MutationObserver는 더 나은 성능과 효율성을 제공합니다.


MutationObserver의 주요 기능

  • DOM 요소의 추가, 삭제 감지
  • 요소의 속성(attribute) 변경 감지
  • 텍스트 콘텐츠의 변경 감지
  • 하위 트리(subtree)의 변화 감지

MutationObserver의 기본 구조

MutationObserver를 사용하기 위해서는 다음과 같은 단계를 거쳐야 합니다.

  1. 옵저버 인스턴스 생성
  2. 관찰할 대상과 설정 정의
  3. 옵저버 시작
  4. 옵저버 중지 (필요 시)

기본 코드 예제

// 1. MutationObserver 인스턴스 생성
const observer = new MutationObserver((mutationRecords, observer) => {
  mutationRecords.forEach((mutation) => {
    console.log('변경 사항 감지:', mutation);
  });
});

// 2. 감시할 대상 요소 선택
const targetElement = document.getElementById('target');

// 3. 감시 옵션 설정
const config = {
  childList: true,       // 자식 노드의 추가 또는 제거 감지
  attributes: true,      // 속성 변경 감지
  characterData: true,   // 텍스트 콘텐츠 변경 감지
  subtree: true          // 하위 트리까지 감지
};

// 4. 옵저버 시작
observer.observe(targetElement, config);

// 5. 변경 테스트를 위한 코드
targetElement.setAttribute('data-status', 'active'); // 속성 변경
targetElement.textContent = '새로운 텍스트';         // 텍스트 콘텐츠 변경
const newElement = document.createElement('div');    // 자식 노드 추가
targetElement.appendChild(newElement);

결과

위의 코드를 실행하면 콘솔에는 다음과 같은 메시지가 출력됩니다.

변경 사항 감지: [MutationRecord 객체]

각 MutationRecord 객체에는 변경된 내용에 대한 상세 정보가 포함됩니다.


MutationObserver의 설정 옵션

옵저버의 감시 동작을 설정하기 위해 observe 메서드에서 사용하는 설정 객체(config)는 다음과 같은 속성을 가집니다.

옵션 설명 데이터 타입 기본값
childList 자식 노드의 추가/제거 감지 boolean false
attributes 속성의 변경 감지 boolean false
characterData 텍스트 콘텐츠의 변경 감지 boolean false
subtree 하위 트리까지 감지 boolean false
attributeFilter 감시할 속성 목록 지정 Array null
attributeOldValue 변경 전 속성 값 저장 boolean false
characterDataOldValue 변경 전 텍스트 콘텐츠 저장 boolean false

예제: 특정 속성만 감지하기

observer.observe(targetElement, {
  attributes: true,
  attributeFilter: ['data-status'] // 특정 속성만 감지
});

targetElement.setAttribute('data-status', 'inactive'); // 감지됨
targetElement.setAttribute('class', 'new-class');      // 감지되지 않음

이 설정은 data-status 속성의 변경만 감지하고, 다른 속성 변경은 무시합니다.


MutationRecord 객체 이해하기

옵저버 콜백 함수로 전달되는 mutationRecords 배열은 각 변경 사항을 나타내는 MutationRecord 객체로 구성되어 있습니다. 이 객체는 다음과 같은 속성을 가집니다.

속성 설명
type 변경 유형 (attributes, childList, characterData)
target 변경이 발생한 요소
addedNodes 새로 추가된 노드 목록
removedNodes 제거된 노드 목록
attributeName 변경된 속성 이름 (속성 변경 시)
oldValue 변경 전 값 (옵션 설정 시)

예제: MutationRecord 속성 확인

const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    console.log('변경 유형:', mutation.type);
    console.log('변경된 요소:', mutation.target);
    if (mutation.type === 'attributes') {
      console.log('변경된 속성:', mutation.attributeName);
      console.log('이전 값:', mutation.oldValue);
    }
  });
});

observer.observe(targetElement, {
  attributes: true,
  attributeOldValue: true
});

targetElement.setAttribute('data-status', 'completed');

MutationObserver의 성능 고려 사항

MutationObserver는 성능이 최적화되어 있지만, 과도한 감시 설정은 여전히 성능 저하를 초래할 수 있습니다. 특히 대규모 DOM 구조나 빈번한 변경이 발생하는 요소를 감시할 때 주의해야 합니다.

성능 최적화 팁

  1. 필요한 변경 사항만 감시하기: childList, attributes, characterData 중 필요한 옵션만 설정합니다.
  2. subtree 사용 최소화: 하위 트리 감시는 범위가 넓어져 성능에 영향을 줄 수 있습니다.
  3. 옵저버 중지: 필요 없는 경우 disconnect() 메서드로 감시를 중지합니다.
// 옵저버 중지
observer.disconnect();

실전 예제: 실시간 댓글 감지하기

<div id="comments">
  <p>첫 번째 댓글</p>
</div>
<button id="addComment">댓글 추가</button>
const commentSection = document.getElementById('comments');
const addCommentButton = document.getElementById('addComment');

const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.type === 'childList') {
      console.log('새로운 댓글이 추가되었습니다.');
    }
  });
});

observer.observe(commentSection, { childList: true });

addCommentButton.addEventListener('click', () => {
  const newComment = document.createElement('p');
  newComment.textContent = '새로운 댓글입니다!';
  commentSection.appendChild(newComment);
});

이 예제에서는 버튼 클릭 시 새로운 댓글이 추가되고, MutationObserver가 이를 감지하여 콘솔에 메시지를 출력합니다.


MutationObserver의 활용 사례

  • 실시간 콘텐츠 업데이트 감지 (예: 채팅, 알림)
  • 동적 폼 검증 (입력 필드 변경 감지)
  • 로딩 상태 관리 (비동기 요소 렌더링 감지)
  • 광고 차단기 탐지 (DOM 변조 감지)

마무리

MutationObserver는 DOM의 변화에 민감하게 반응해야 하는 웹 애플리케이션에서 매우 유용한 도구입니다. 성능과 효율성을 고려하여 필요한 부분만 감시하고, 콜백 함수를 적절히 활용하면 더 나은 사용자 경험을 제공할 수 있습니다.

 

저작자표시 비영리 동일조건 (새창열림)

'FE > WEB' 카테고리의 다른 글

iframe과 통신하는 방법  (0) 2025.02.03
Web Worker란 무엇인가?  (4) 2025.02.02
URL과 URLSearchParams 활용법  (0) 2025.02.01
FE/WEB 추천 글
more
  • iframe과 통신하는 방법
    iframe과 통신하는 방법2025.02.03
  • Web Worker란 무엇인가?
    Web Worker란 무엇인가?2025.02.02
  • URL과 URLSearchParams 활용법
    URL과 URLSearchParams 활용법2025.02.01
FRONTMAN

검색

250x250

방문자 수

Total
Today
Yesterday

카테고리

  • 분류 전체보기 (54)
    • Language (48)
      • JavaScript (15)
      • TypeScript (14)
      • Python (14)
      • Dart (5)
      • Java (0)
    • FE (6)
      • WEB (4)
      • React (0)
      • Flutter (1)
    • CS (0)
      • Algorithm (0)
      • Network (0)
    • DevOps (0)

공지사항

  • 전체보기

최근 글

인기 글

태그

  • Modules
  • async
  • CLASS
  • function
  • frontend
  • Object
  • JavaScript
  • js
  • 타입
  • inline frame
  • Python
  • npm
  • DART
  • 리스트
  • 자바스크립트
  • list
  • await
  • nodejs
  • 파이썬
  • OOP
  • Import
  • Interface
  • typeScript
  • web
  • tuple
  • export
  • Flutter
  • Type
  • 타입스크립트
  • 웹

최근 댓글

FRONTMAN :: hahekaku
CopyrightBluemivDesigned byBluemiv

티스토리툴바