Advanced Single Page Application (SPA) Galleries

Overview

When your site is an SPA, the Social Commerce snippet, loaded in the <head> of the page, will not be reloaded when navigating between pages. This means that our scripts will not auto-initialize Galleries on page load and so they must be initialized manually using our advanced integration API.

Initializing Galleries on your SPA

These instructions focus on integrating Social Commerce Galleries on single page applications.

1. Integrate the script

Integrate the site script into the page <head> like normal. This will load our site.js asynchronously by default. We prevent potential race conditions by use of window.crl8.ready, which is elaborated on below.

2. Add Attribute

Before placing the container <div>, the data-crl8-auto-init="false" attribute must be added to the <div>. This places loading control over the Gallery into your hands. The final container will be a similar variation of this based on your specific data-crl8-container-id:

<div data-crl8-container-id="homepage" data-crl8-auto-init="false"> 

3. Create and route the gallery

Create a Gallery using our advanced integration API which is accessible via JavaScript on the window.crl8 global object.

Most of the SPAs use a routing mechanism to navigate users from one page to another. Hence, it is important to clean up the gallery before navigating the user to another page.

The example below demonstrates a React implementation using a single useEffecthook to initialize the Gallery on component mount and destroy it on unmount—for example, when the user navigates to a new page.​​​​​​​​​​​​​​​​

ℹ️

Note

The exact implementation will vary depending on your codebase and will require a developer.

Example React Code

import { useEffect } from 'react';

function MyPage() {
  // Define the gallery name from your div
  const galleryId = 'homepage';

  useEffect(() => {
    // 1. CREATE GALLERY
    if (window.crl8 && window.crl8.ready) {
      // window.crl8.ready fires the callback once the crl8 api is available
      window.crl8.ready(function () {
        // Use the actual gallery name here
        window.crl8.createExperience(galleryId);
      });
    }

    // 2. CLEANUP / DESTROY GALLERY (routing)
    return () => {
      if (window.crl8 && window.crl8.ready) {
        // to be safe, use crl8.ready again or check for presence of
        // window.crl8.destroyExperience before calling the function
        window.crl8.ready(function () {
          // Use the actual gallery name here
          window.crl8.destroyExperience(galleryId);
        });
      }
    };
  }, [galleryId]); // The effect depends on the galleryId

  // Render the div that the API will use
  return <div data-crl8-container-id={galleryId} data-crl8-auto-init='false' />;
}

export default MyPage;