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 the Gallery
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
class 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 page
window.crl8.ready(function() {
// Use the actual gallery name here
window.crl8.createExperience('homepage');
});
}
}
render() {
return <div data-crl8-container-id="homepage" data-crl8-auto-init="false" />}
}
4. Routing
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
class 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 function
window.crl8.ready(function() {
// Use the actual gallery name here
window.crl8.destroyExperience('homepage');
});
}
}
}
Updated about 1 year ago