Tutorial

Lazy Loading Scripts

Published on December 21, 2016
author

Alligator.io

Lazy Loading Scripts

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) {
    return;
  }

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

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) {
  loadScript('/path/to/search-script.js');
});

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Alligator.io

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

This comment has been deleted

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Become a contributor for community

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    DigitalOcean Documentation

    Full documentation for every DigitalOcean product.

    Resources for startups and SMBs

    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

    Get our newsletter

    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

    New accounts only. By submitting your email you agree to our Privacy Policy

    The developer cloud

    Scale up as you grow — whether you're running one virtual machine or ten thousand.

    Get started for free

    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

    *This promotional offer applies to new accounts only.