đSteps to Initialise Live Updates with JS
Initialising Live Updates with the Object Constructor in JavaScript
Until this point, we have focussed on how to use our data-attributes to configure the Live Updates API. In this guide we'll show you how to initialise with JavaScript. This is intended for advanced users, who may wish to extend the functionality.
1) Include the JS
Similar to the Getting Started Section, include the following Liquid to asyncronously load the JS only once per page.
We'll skip this snippet of code in the next few examples, for brevity.
2) Add an event-listener to watch for the Script to load
Since the JS runs asynchronously, the constructor function cannot be invoked immediately. We provide a custom event on the document which can be listened for so that we know when the script is ready.
3) Passing in the Public Key and Initialising
First, include the module JavaScript via CDN and generate the public_key on the server-side as shown earlier in this article.
Next, you'll need to pass the public_key to your JavaScript. You can either:
a) write the JS in an inline <script></script>
tag and output the public_key straight into the JS using Liquid
b) or you can use Liquid to output the public_key into a data-attribute and fetch it from the DOM when needed. Tip: You may not wish to use a different attribute other than data-sg-live-update-key
, as this will trigger the default event-listeners in the module if present.
c) Or you can use Liquid to output the public key as a global JS variable in an inline script tag.
Inline Script Tag example:
Refer to the API Reference for the full range of available options which can be used while initialising with JS.
4) Add an HTML control and attach an Event Listener
5) Trigger a Live Update when the Event Callback runs
Earlier we stored a reference to the Live Update instance in a variable called section
. We can use this now to run the liveUpdate
method inside the event callback function.
You can find the full reference for this method and others in the (API Reference)[/documentation/sitebuilder/live_updates/API_reference]. Other methods can be run on the instance in the same way.
\
Last updated