Using Clerk.js with single-page apps

Control the rendering with JS.

When a page is loaded the first time, the Clerk.js library automatically fires a function to render all Content blocks on that page.

However, for single-page apps using frameworks like vue.js or next.js, pages are rendered with javascript rather than a standard page load.

Due to this, you need to control the rendering with Clerk.js to match how you load pages in the single-page app.

Include Clerk.js

Clerk.js only needs to be loaded once, when the site is initially loaded. After this, the library will be availble throughout the session. Include it just before the </head> in your HTML:

<!-- Start of Clerk.io E-commerce Personalisation tool - www.clerk.io -->
<script type="text/javascript">
    (function(w,d){
    var e=d.createElement('script');e.type='text/javascript';e.async=true;
    e.src='https://cdn.clerk.io/clerk.js';
    var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(e,s);
    w.__clerk_q=w.__clerk_q||[];w.Clerk=w.Clerk||function(){w.__clerk_q.push(arguments)};
    })(window,document);

    Clerk('config', {
    key: 'INSERT_PUBLIC_API_KEY'
    });
</script>
<!-- End of Clerk.io E-commerce Personalisation tool - www.clerk.io -->

Control rendering

This is done with the function Clerk("content", "#ID")

Every time a page is loaded, do these steps in order:

  • Add the Clerk snippet to the HTML. Make sure it has a unique ID you can target
  • Run Clerk("content", "#ID") to render it

When the visitor leaves the page, destroy the snippet, to ensure you can render it again if the visitor returns to the same page. This is to ensure Clerk.js does not see the snippet as previously rendered, causing it to not visualise.

Example:

<span 
  id="clerk-custom-snippet"
  data-template="@home-page-visitor-recommendations">
</span>

<script>
  Clerk("content", "#clerk-custom-snippet")
</script>

For more info check our documentation for Dynamic Content here