addEventListener passive 옵션 (touch, wheel)

{ kim hyo }·2023년 11월 28일

passive 스크롤 성능 향상 옵션

false 설정시 touch, wheel 이벤트 발생할때 preventDefault를 통해 이벤트 자체를 막을수 있다.(scroll event X)
하지만 true일 경우 preventDefault 쓰면 에러가 발생한다.
_Unable to preventDefault inside passive event listener invocation.

passive true일 경우, 이 수신기 내에서 preventDefault()를 절대 호출하지 않을 것임을 나타내는 불리언 값입니다. 이 값이 true인데 수신기가 preventDefault()를 호출하는 경우, 사용자 에이전트는 콘솔에 경고를 출력하는 것 외에 아무런 동작도 하지 않습니다. 명시하지 않을 경우의 기본 값은 false지만, Safari와 Internet Explorer를 제외한 브라우저에서 wheel (en-US), mousewheel (en-US), touchstart (en-US), touchmove (en-US) 이벤트에서의 기본 값은 true입니다.

예시

마우스휠에 동작하며 슬라이드처럼 한페이지씩 넘어감

<html lang="ko">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
		<style>
			* {
				padding: 0;
				margin: 0;
				box-sizing: border-box;
			}
			::-webkit-scrollbar {
				display: none;
			}
			section {
				min-height: 100%;
				background-color: #eee;
				border-bottom: 4px solid #888;
			}
		</style>
	</head>
	<body>
		<section><h2>섹션 1</h2></section>
		<section><h2>섹션 2</h2></section>
		<section><h2>섹션 3</h2></section>
		<section><h2>섹션 4</h2></section>
		<section><h2>섹션 5</h2></section>
		<section><h2>섹션 6</h2></section>
		<section><h2>섹션 7</h2></section>
		<script>
			let wheel = true;
			const wheelCont = document.querySelectorAll("section");
			window.addEventListener(
				"wheel",
				function (e) {
					e.preventDefault();
					if (wheel) {
						wheel = false;
						if (e.deltaY > 0) {
							window.scrollTo({top: window.scrollY + window.innerHeight, behavior: "smooth"});
						} else {
							window.scrollTo({top: window.scrollY - window.innerHeight, behavior: "smooth"});
						}
						setTimeout(function () {
							wheel = true;
						}, 1000);
					}
				},
				{passive: false}
			);
		</script>
	</body>
</html>


touch, wheel이벤트에서 passive false여야지만 preventDefault를 사용 가능함을 기억하자!
profile
작업하다 알게 되는 지식 정리 👩🏻‍💻

0개의 댓글