Lazy Loading Scripts


While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

The scripts needed for the search functionality of this website are only loaded when the search bar is focused. This way, they’re only ever loaded for people who decide to use the search function, and bandwidth as well as page weight can be drastically reduced. Only a small fraction of visitors will use the search after all, so why incur the cost each time?

To accomplish this simple lazy load technique, let’s first define a function that we’ll call loadScript:

function loadScript(url) {
  let isLoaded = document.querySelectorAll('.search-script');
  if(isLoaded.length > 0) {

  let myScript = document.createElement("script");
  myScript.src = url;
  myScript.className = 'search-script';

The function first checks if the script has already been loaded, in which case it’ll just return instead of trying to load it multiple times. We then create a script element with document.createElement, give it the passed-in url as the value to it’s src attribute, give it the class name for our check to work, and then append this new script element to the body element.

The last step is to simply setup an event listener on the search input and call our loadScript function with the url to our script:

var searchInput = document.querySelector('.algolia__input');
searchInput.addEventListener('focus', function(e) {

Obviously this mean that in theory there’s a short delay between focusing in the search box and the script being available to use. In most cases it shouldn’t be a problem, and in this case the real time search picks up as soon as the script is fully loaded.

Creative Commons License