포털 실습: 웹에서 원활한 탐색

제안된 Portals API가 탐색 UX를 개선하는 방법을 알아보세요.

Yusuke Utsunomiya
Yusuke Utsunomiya

페이지 로드가 빠르게 이루어지도록 하는 것은 우수한 사용자 경험을 제공하는 데 핵심적인 요소입니다. 하지만 우리가 간과하는 영역 중 하나는 페이지 전환, 즉 사용자가 페이지 간에 이동할 때 표시되는 내용입니다.

포털이라는 새로운 웹 플랫폼 API 제안은 사용자가 사이트를 탐색할 때 환경을 간소화하여 이를 지원하는 것을 목표로 합니다.

포털 사용 사례 보기:

포털을 사용한 원활한 삽입 및 탐색 Adam Argyle이 만들었습니다.

포털에서 가능한 작업

단일 페이지 애플리케이션 (SPA)은 멋진 전환을 제공하지만 빌드 복잡성이 높아집니다. 멀티 페이지 애플리케이션 (MPA)은 빌드하기가 훨씬 쉽지만 페이지 사이에 빈 화면이 표시됩니다.

포털은 MPA의 낮은 복잡성과 SPA의 원활한 전환이라는 두 가지 장점을 모두 제공합니다. 임베딩을 허용한다는 점에서 <iframe>와 유사하지만, <iframe>와 달리 콘텐츠로 이동하는 기능도 제공합니다.

백문이 불여일견입니다. 먼저 Chrome Dev Summit 2018에서 선보인 내용을 확인해 보세요.

기존 탐색에서는 브라우저가 도착 페이지의 렌더링을 완료할 때까지 사용자가 빈 화면을 보며 기다려야 합니다. 포털을 사용하면 사용자는 애니메이션을 경험하고 <portal>는 콘텐츠를 미리 렌더링하고 원활한 탐색 환경을 만듭니다.

포털 이전에는 <iframe>를 사용하여 다른 페이지를 렌더링할 수 있었습니다. 페이지에서 프레임을 이동하는 애니메이션을 추가할 수도 있습니다. 하지만 <iframe>는 콘텐츠로 이동할 수 없습니다. 포털은 이러한 격차를 해소하여 흥미로운 사용 사례를 가능하게 합니다.

포털 사용해 보기

about://flags를 통해 사용 설정

실험용 플래그를 전환하여 Chrome 85 이상 버전에서 포털을 사용해 보세요.

  • 동일 출처 탐색에 about://flags/#enable-portals 플래그를 사용 설정합니다.
  • 교차 출처 탐색을 테스트하려면 about://flags/#enable-portals-cross-origin 플래그도 사용 설정합니다.

포털 실험의 초기 단계에서는 --user-data-dir 명령줄 플래그를 설정하여 테스트에 완전히 별도의 사용자 데이터 디렉터리를 사용하는 것이 좋습니다. 포털이 사용 설정되면 DevTools에서 새로운 HTMLPortalElement가 있는지 확인합니다.

HTMLPortalElement를 보여주는 DevTools 콘솔의 스크린샷

포털 구현

기본 구현 예를 살펴보겠습니다.

// Create a portal with the wikipedia page, and embed it
// (like an iframe). You can also use the <portal> tag instead.
portal = document.createElement('portal');
portal.src = 'https://en.wikipedia.org/wiki/World_Wide_Web';
portal.style = '...';
document.body.appendChild(portal);

// When the user touches the preview (embedded portal):
// do fancy animation, e.g. expand …
// and finish by doing the actual transition.
// For the sake of simplicity, this snippet will navigate
// on the `onload` event of the Portals element.
portal.addEventListener('load', (evt) => {
   portal.activate();
});

간단한 작업입니다. DevTools 콘솔에서 이 코드를 사용해 보세요. Wikipedia 페이지가 열립니다.

포털 스타일 미리보기 데모 GIF

Chrome Dev Summit에서 보여드린 것과 같이 위의 데모와 동일하게 작동하는 것을 빌드하려면 다음 스니펫을 참고하세요.

// Adding some styles with transitions
const style = document.createElement('style');
style.innerHTML = `
  portal {
    position:fixed;
    width: 100%;
    height: 100%;
    opacity: 0;
    box-shadow: 0 0 20px 10px #999;
    transform: scale(0.4);
    transform-origin: bottom left;
    bottom: 20px;
    left: 20px;
    animation-name: fade-in;
    animation-duration: 1s;
    animation-delay: 2s;
    animation-fill-mode: forwards;
  }
  .portal-transition {
    transition: transform 0.4s;
  }
  @media (prefers-reduced-motion: reduce) {
    .portal-transition {
      transition: transform 0.001s;
    }
  }
  .portal-reveal {
    transform: scale(1.0) translateX(-20px) translateY(20px);
  }
  @keyframes fade-in {
    0%   { opacity: 0; }
    100% { opacity: 1; }
  }
`;
const portal = document.createElement('portal');
// Let's navigate into the WICG Portals spec page
portal.src = 'https://wicg.github.io/portals/';
// Add a class that defines the transition. Consider using
// `prefers-reduced-motion` media query to control the animation.
// https://developers.google.com/web/updates/2019/03/prefers-reduced-motion
portal.classList.add('portal-transition');
portal.addEventListener('click', (evt) => {
  // Animate the portal once user interacts
  portal.classList.add('portal-reveal');
});
portal.addEventListener('transitionend', (evt) => {
  if (evt.propertyName == 'transform') {
    // Activate the portal once the transition has completed
    portal.activate();
  }
});
document.body.append(style, portal);

또한 포털을 사용하여 웹사이트를 점진적으로 개선하기 위해 기능 감지를 쉽게 수행할 수 있습니다.

if ('HTMLPortalElement' in window) {
  // If this is a platform that have Portals...
  const portal = document.createElement('portal');
  ...
}

포털의 느낌을 빠르게 경험하고 싶다면 uskay-portals-demo.glitch.me를 사용해 보세요. Chrome 85 이상 버전으로 액세스하고 실험용 플래그를 사용 설정해야 합니다.

  1. 미리보려는 URL을 입력합니다.
  2. 그러면 페이지가 <portal> 요소로 삽입됩니다.
  3. 미리보기를 클릭합니다.
  4. 애니메이션이 끝나면 미리보기가 활성화됩니다.

포털을 사용하는 Glitch 데모를 사용하는 GIF

사양 확인하기

Google은 웹 인큐베이션 커뮤니티 그룹 (WICG)에서 포털 사양을 활발하게 논의하고 있습니다. 빠르게 시작하려면 주요 시나리오를 살펴보세요. 다음은 숙지해야 할 세 가지 중요한 기능입니다.

  • <portal> 요소: HTML 요소 자체입니다. API는 매우 간단합니다. src 속성, activate 함수, 메시지 인터페이스 (postMessage)로 구성됩니다. activate는 활성화 시 <portal>에 데이터를 전달하는 선택적 인수를 사용합니다.
  • portalHost 인터페이스: window 객체에 portalHost 객체를 추가합니다. 이렇게 하면 페이지가 <portal> 요소로 삽입되어 있는지 확인할 수 있습니다. 또한 호스트로 다시 메시지를 보내는 인터페이스 (postMessage)를 제공합니다.
  • PortalActivateEvent 인터페이스: <portal>가 활성화될 때 실행되는 이벤트입니다. adoptPredecessor라는 깔끔한 함수가 있는데, 이 함수를 사용하면 이전 페이지를 <portal> 요소로 가져올 수 있습니다. 이를 통해 두 페이지 간에 원활한 탐색과 구성된 환경을 만들 수 있습니다.

기본 사용 패턴을 넘어 살펴보겠습니다. 다음은 포털로 할 수 있는 작업의 일부 목록과 샘플 코드입니다.

<portal> 요소로 삽입할 때 스타일 맞춤설정

// Detect whether this page is hosted in a portal
if (window.portalHost) {
  // Customize the UI when being embedded as a portal
}

<portal> 요소와 portalHost 간의 메시지

// Send message to the portal element
const portal = document.querySelector('portal');
portal.postMessage({someKey: someValue}, ORIGIN);

// Receive message via window.portalHost
window.portalHost.addEventListener('message', (evt) => {
  const data = evt.data.someKey;
  // handle the event
});

<portal> 요소 활성화 및 portalactivate 이벤트 수신

// You can optionally add data to the argument of the activate function
portal.activate({data: {somekey: 'somevalue'}});

// The portal content will receive the portalactivate event
// when the activate happens
window.addEventListener('portalactivate', (evt) => {
  // Data available as evt.data
  const data = evt.data;
});

선행 작업 검색

// Listen to the portalactivate event
window.addEventListener('portalactivate', (evt) => {
  // ... and creatively use the predecessor
  const portal = evt.adoptPredecessor();
  document.querySelector('someElm').appendChild(portal);
});

내 페이지가 이전 버전으로 채택되었음을 알 수 있음

// The activate function returns a Promise.
// When the promise resolves, it means that the portal has been activated.
// If this document was adopted by it, then window.portalHost will exist.
portal.activate().then(() => {
  // Check if this document was adopted into a portal element.
  if (window.portalHost) {
    // You can start communicating with the portal element
    // i.e. listen to messages
    window.portalHost.addEventListener('message', (evt) => {
      // handle the event
    });
  }
});

포털에서 지원하는 모든 기능을 결합하면 정말 멋진 사용자 환경을 구축할 수 있습니다. 예를 들어 아래 데모는 포털이 웹사이트와 서드 파티 삽입 콘텐츠 간에 원활한 사용자 환경을 지원하는 방법을 보여줍니다.

사용 사례 및 요금제

포털에 대한 이 간단한 둘러보기가 마음에 드셨기를 바랍니다. 여러분의 다음 행보도 기대하며 응원하겠습니다. 예를 들어 제품 카테고리 목록 페이지에서 베스트셀러 제품의 페이지를 사전 렌더링하는 것과 같은 중요한 탐색에 포털을 사용할 수 있습니다.

또 한 가지 중요한 점은 포털을 <iframe>처럼 교차 출처 탐색에 사용할 수 있다는 것입니다. 따라서 서로 교차 참조하는 웹사이트가 여러 개 있는 경우 포털을 사용하여 두 개의 서로 다른 웹사이트 간에 원활한 탐색을 만들 수도 있습니다. 이 교차 출처 사용 사례는 포털에만 있는 매우 독특한 사례이며 SPA의 사용자 경험을 개선할 수도 있습니다.

의견 보내기

포털은 Chrome 85 이상 버전에서 실험할 수 있습니다. 커뮤니티의 의견은 새로운 API 설계에 매우 중요하므로 사용해 보고 의견을 알려주세요. 기능 요청이나 의견이 있으면 WICG GitHub 저장소로 이동하세요.