Advanced Single Page Application (SPA) Galleries Guide
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.
- 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.
- 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:
1<div data-crl8-container-id="homepage" data-crl8-auto-init="false">
- You now need to create the Gallery using our advanced integration API. This API is accessed via Javascript on the window.crl8 global object. How you leverage the API will depend on the specific nature of your codebase and will require the involvement of a developer.
React Code Example – Examples are shown in React but our advanced integration API can be used with other libraries as well
1234567891011121314151617class myPage extends React.Component {componentDidMount() {if (window.crl8 && window.crl8.ready) {// window.crl8.ready fires the callback once the crl8 api is available for use on the pagewindow.crl8.ready(function() {// Use the actual gallery name herewindow.crl8.createExperience('homepage');});}}render() {return <div data-crl8-container-id="homepage" data-crl8-auto-init="false" />}} - Most SPAs use routing to move users from one “page” to another. For this reason, it is also important that you “clean up” before routing the user to another page.
React Code Example
123456789101112class myPage extends React.Component {componentWillUnmount() {if (window.crl8 && window.crl8.ready) {// to be safe, use crl8.ready again or check for presence of// window.crl8.destroyExperience before calling the functionwindow.crl8.ready(function() {// Use the actual gallery name herewindow.crl8.destroyExperience('homepage');});}}}