Speed up your storefront by loading scripts on demand

Some service integrations load needlessly on each page, increasing page load times.

Rob Johnson

By Rob Johnson

Fri Mar 10 2023

Some services require you to load their widget on every page, even if it's unlikely that a user will use it. An example of this is a customer support widget. Although a customer may need to use it at some point, most page views won't require it.

This can be problematic if the widget is a floating widget that may interfere with important elements on your page, such as the add-to-cart button. Additionally, loading the widget on every page can increase the total load time and size of each page. This can negatively impact both the customer's experience, especially if they're on a mobile internet connection, and your website's SEO due to slowing down each page.

In this example, we're loading a customer support widget from Solvvy. To ensure the widget only loads when a customer wants to use it, I've written the following JavaScript function which checks whether the widget has already loaded. If it hasn't, the function adds the script tag to the page and executes the JavaScript.

function launchSolvvy() {
  if ( window.Solvvy ) {
    Solvvy.open();
  } else {
    // Create a script element
    const script = document.createElement('script');
    script.src = 'https://cdn.solvvy.com/deflect/customization/{name}/solvvy.js';

    // Append the script element to the document head
    document.head.appendChild(script);

    document.addEventListener("solvvy_ready", () => {
      console.log("Solvvy widget loaded");
      // Open chat window
      Solvvy.open();
    });
  }
}

Then I created a simple link for "Chat" with the following HTML.

<a onclick="launchSolvvy()" title="Open Chat">Chat</a>

Instead of loading another webpage, you can use an <a> tag to initiate the launchSolvvy() function that we just added.

Once the script is loaded, you can use the services API's as you need

This particular widget from Solvvy has an API tha can perform certain functions. This includes methods to open and close the widget. Once we know the widget has loaded by listening for the solvvy_ready event, when can then open the widget by simply calling Solvvy.open().

User Experience

This approach leads to faster page load times for customers, and the widget will load immediately when they click the link. To improve the user experience further, you can add a loading icon to the page once the link is pressed, in case the request for the javascript file to load and execute takes a few seconds.

# commerce 14 # seo 5 # tools 6 # amazon 1 # sql 4 # shopify 9 # javascript 13 # projects 4 # css 2 # git 2 # php 3 # analytics 4 # api 6 # monitoring 2 # python 2 # aws 2