in Platform Updates

Load Widget on Demand

Krzysztof Kraus in Programming, on July 12, 2022

Have you ever wanted to load your beautiful chat widget for your customers, but only when they accept a cookie consent prompt on your website? Or to load it only for logged-in customers? It’s possible with our chat widget!

In fact, it’s possible without the need of creating an elaborate code based on if statements just to load a single snippet of code. All of that (and more!) is possible with the use of our asynchronous Initialization JavaScript API feature!

In this article, we will answer the following questions:

  • What is asyncInit and what are the requirements to use this function?
  • When can you use it?
  • When should you definitely not use it?
  • How do you enable this option in chat widget and implement it on your website?

What is asyncInit?

AsyncInit* is an optional feature available for each customer using our chat widget. With the use of a simple JavaScript API method, you can choose the exact moment when your beloved bubble will be loaded on a website.

Before showing you how it works, we’d like to guide you through some of the use cases in which you should and maybe shouldn’t use asyncInit. Because, as someone wise once said, “With great features come great responsibilities.”

*Async (short from asynchronous) refers to the execution of the task after another is completed. This method is most commonly used when waiting for data download, such as when you want to display an image once it is downloaded.

LiveChat AsyncInit image

When should you use asyncInit?

There are many situations where you may want to load a widget on demand or when a specific action takes place. Just to give you a better idea of when it may come in handy, here are two of the most common use cases borrowed straight from our customers!

💡 Consider using asyncInit when there’s a cookie manager implemented on your website or other solutions required by GDPR.

As a website owner, whether running a store or a news service, one of the most crucial factors when building a trustworthy user experience is making sure that your customers can make informed decisions. One of the ways that will allow you to achieve this is to let your customers know what data or cookies are processed by you or the 3rd party vendors used on your page.

The most common way of doing so is to install a cookie manager or a prompt that will allow your customers to read the information about cookies and accept or decline them. But what’s the problem with that? Many cookie managing solutions are not preventing 3rd party software from actually being initialized in the background, which actually defeats their purpose. And even if they do, they may not work correctly with software like LiveChat.

With the use of asyncInit, you can work around that by simply calling the initialization method whenever a user clicks on the Accept button. There’s no advanced coding required, and you can rest assured that LiveChat will comply with the cookie policy on your website!

💡 Use asyncInit when the widget is loaded only when specific conditions are met.

AsyncInit comes in handy if you are also considering serving your widget in specific situations. For example, if you’d like to show your widget only to logged-in customers or if a customer performs a specific sequence of actions. You can initialize a chat widget by calling a simple JS API method whenever a user meets the conditions you had in mind.

LiveChat AsyncInit second image

What should you remember when using asyncInit?

As we’d love for you to use the full potential of your chat widget, you should think about situations where using asyncInit may not be the best option. Remember that out of the box, LiveChat comes with various tracking functionalities, including features like the Targeted Messages or Customers Traffic features, allowing you to engage with your customers manually – so those features will not work on your website when the widget is not initialized.

How do you enable asyncInit and implement it on your website?

Before we begin, make sure that the LiveChat script tag version used on your website points to version 2.0 (at least). To do that, you can call the LiveChatWidget.scriptTagVersion() function in the Console when browsing through your website. If you are currently rocking the older version of our script tag, you can get the new one under Settings -> Channel -> Website or by clicking here. Just remember to log in to your LiveChat account before proceeding.

Now that everything is in place, it is time to enable the asyncInit. To do that, you need to add the __lc.asyncInit property to your widget’s snippet and set its property to “true”. After doing so, your code should look like this:

<!-- Start of LiveChat (www.livechatinc.com) code -->
<script>
  window.__lc = window.__lc || {};
  window.__lc.license = <LICENSE_NUMBER>;
  // Add the asyncInit property after your license number
  window.__lc.asyncInit = true;
  ;(function(n,t,c){function i(n){return e._h?e._h.apply(null,n):e._q.push(n)}var e={_q:[],_h:null,_v:"2.0",on:function(){i(["on",c.call(arguments)])},once:function(){i(["once",c.call(arguments)])},off:function(){i(["off",c.call(arguments)])},get:function(){if(!e._h)throw new Error("[LiveChatWidget] You can't use getters before load.");return i(["get",c.call(arguments)])},call:function(){i(["call",c.call(arguments)])},init:function(){var n=t.createElement("script");n.async=!0,n.type="text/javascript",n.src="https://cdn.livechatinc.com/tracking.js",t.head.appendChild(n)}};!n.__lc.asyncInit&&e.init(),n.LiveChatWidget=n.LiveChatWidget||e}(window,document,[].slice))
</script>
<!-- End of LiveChat code -->

Now the asyncInit option is enabled!

From now on, you can load a chat widget and its resources on demand by calling the LiveChatWidget.init() JavaScript function.

Keeping the cookie consent scenario in mind, you can, for example, target the Accept cookies button and initialize the widget whenever a user clicks on it.

Here’s a simple example of how it can look code-wise:

<html>
  <head>
    <!-- Start of LiveChat (www.livechatinc.com) code -->
    <script>
      window.__lc = window.__lc || {};
      window.__lc.license = <LICENSE_NUMBER>;
      window.__lc.asyncInit = true;
      /* rest of the standard snippet code */
    </script>
    <!-- End of LiveChat code -->
  </head>
  <body>
    <button id="cookies-confirmation">Accept cookies</button>
    <script>
      var chatButton = document.getElementById('cookies-confirmation')
      chatButton.addEventListener('click', function() {
        // Save an agreedToCookies item in browser’s localStorage and initialize Chat Widget when the user clicks on a button
        window.localStorage.setItem('agreedToCookies', 'yes')
        LiveChatWidget.init()
      })
    </script>
  </body>
</html>

Please remember that once the asyncInit option is enabled, you will need to make sure that the LiveChatWidget.init() function is called whenever a user navigates to another page with our code and has accepted the cookie consent! Otherwise the widget will be gone after each page reload or navigation event. A good practice would be to set up an additional statement that will call this function whenever a customer is browsing through your website with the __lc.asyncInit parameter added to your LiveChat’s snippet.

Here’s a simple example on how to do so, based on the item that we saved in the localStorage above:

<script>
  const cookieConsent = window.localStorage.getItem("agreedToCookies");
  if (cookieConsent === "yes") {
    LiveChatWidget.init();
  }
</script>

And that’s it!

Remember that the possibilities are endless - whether it is the cookie consent scenario manager we mentioned, an elaborate condition based on when you’d like to load the widget or showing it only for logged in users, asyncInit is here to make your dreams come true.


See other Platform Updates

App Review Offer

Each application created by Application Provider (also known as Developer) in the LiveChat Developer Program has to go through a standard….

Read more

Live Coding Session: Breaking down the details of LiveChat Properties

Mark July 6th in your calendars, as we’re running another live coding session! Join us to understand the details of LiveChat properties….

Read more
See all updates