코-딩/Javascript

Javascript - MutationObserver(화면 감지)

ㅋㅂㅋ 2022. 4. 15. 11:49

javascript 사용 시 함수를 매번 loop를 태워 돌리기엔 부하가 심하고 특정 상황에 변경만을 감지하여 작동하고 싶을 경우가 있다. 그러한 경우 MutationObserver를 사용하면 된다.

 

MutationObserver( 변경을 감지할 위치, 무엇에대한 변경인지 )

 

let detectScreen = function () {

    let target = document.querySelector("html");

    let option = {

        attributes: true, //attributes, childList, characterData 셋 중 하나는 꼭 true여야 한다.

        childList: true,

        characterData: true,

        subtree: true //후손들의 작동까지 감지

    }

    let screenDectector = new MutationObserver( mutations => {

        console.log("+++++++");

        //감지된 변경에 따른 작동 로직 작성

        console.log("+++++++");

    }

    screenDectector.observe( target, option );

    //screenDectector.disconnect(); //화면 감지를 그만할 때

}

 

detectScreen();

 

++++++++++++++++++++++++++

 

여기서 target인 html이 로드가 안됬을 경우 기다리기 위해서 window.setTimeout를 이용해주면 좋다.

 

//target 하위에 작성

if(!target) {

    window.setTimeout(detectScreen, 시간);

    return;

}

 

화면 변경을 감지하면서, 원하는 위치가 담길 때 까지의 시간을 벌 수 있다.

 

출처 : 

 

MutationObserver - Web API | MDN

MutationObserver 는 개발자들에게 DOM 변경 감시를 제공합니다. DOM3 이벤트 기술 설명서에 정의된 Mutation Events 를 대체합니다.

developer.mozilla.org