기타

IOS Chrome, Safari에서 Smooth Scroll이 안될 때 해결법

Joonfluence 2021. 12. 27.

본론

글이 짧으므로, 본론만 이야기하겠습니다.

html {
 scroll-behavior: smooth;
}

CSS로 간단하게 smooth-scroll 효과를 위와 같이 줄 수 있습니다.

 document.getElementById(아이디).scrollIntoView({
   behavior: 'smooth',
 });

혹은 위의 예제처럼 ScrollIntoView 함수를 사용하여 해당 영역으로 이동시킬 수 있습니다. 그리고 Scroll option으로 smooth를 주면 부드럽게 스크롤링이 되는데요.

 

문제는 이 옵션이 IOS Chrome, Safari에서는 지원되지 않는다는 점입니다. (아래 참고 링크를 통해 확인할 수 있습니다.) 그래서 a 태그를 누르면 페이지가 깜빡이듯 페이지 깜빡임은 물론, smooth scrolling도 되지 않습니다. 그러나 문서를 살펴보면, "Not Supported by default but can be enabled"라고 적혔듯, 문제 해결이 불가능한 것은 아닙니다. 그래서 열심히 서칭해본 결과, seamless-scroll-polyfill 패키지에서 해당 기능을 지원해주는 것을 확인 할 수 있었습니다.

npm install seamless-scroll-polyfill; 

설치가 끝나면, elementScrollIntoView 메소드를 호출하여, 기존 ScrollIntoView를 대신해줍니다.

import { elementScrollIntoView } from 'seamless-scroll-polyfill';

  elementScrollIntoView(document.getElementById(아이디), {
    behavior: 'smooth',
  });
};

그러면 성공적으로 동작하는 것을 확인하실 수 있을 것입니다.

 

Import Error 해결법

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module

해당 모듈을 import 할 때, 문제가 발생할 수 있습니다. 저 역시 그랬는데요. node_modules/lib/bundle.js 에서 require 방식으로 모듈을 불러오는 지점 때문이었습니다. 이미 프로젝트에서는 ESM 방식으로 모듈을 불러오고 있었는데 말이죠. 저 같은 경우에는 nextjs를 활용해 프로젝트를 진행하고 있었으므로 next-transpile-modules을 설치하고 next.config.js에 하단과 같이 사용할 모듈과 함께 설정해주었습니다.

const withTM = require('next-transpile-modules')(['seamless-scroll-polyfill'], { unstable_webpack5: true });
module.exports = withTM();

 

참고한 링크

https://caniuse.com/?search=scroll-behavior
https://stackoverflow.com/questions/65552682/scrollintoview-is-not-working-as-expected-in-safari-browser
https://blog.smilecat.dev/posts/next-transpile-modules

반응형

댓글