search ]

Lazy Loading Scripts

The script that activates the search option on Savvy Blog is loaded only when the user clicks on the search icon in the top bar. So, the functionality of the search is not particularly complex or anything like that, but do you see a reason to load it when the visitor doesn’t intend to use the blog’s search option at all?

Moreover, the purpose of this post is to demonstrate a technique for scripts that are much more complex. This way, you can significantly reduce the page weight and even shorten the time required for JavaScript execution. Consequently, you can improve loading time and likely achieve better Core Web Vitals metrics.

For our purposes, to use this Lazy Loading technique, let’s define a function called 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 is already loaded. If it is, the function simply ends without trying to load the script multiple times. Then, we create an element of type script using document.createElement and pass the URL that will be used for the src attribute of the lazily loaded script.

We add the relevant class for the previous check (whether the script is already loaded or not), and then append the script to the body element of the page.

The last action is simply to define an event listener that listens for a click on the search icon on the site. When this happens, we call the loadScript function with the URL of our script.

let searchInput = document.querySelector('#trigger-overlay');
searchInput.addEventListener('click', function (e) {
    loadScript('/path/to/search.js');
});

In the case of this blog, I’m also displaying the search popup before calling the script using loadScript.

This concludes our process. We saved loading a specific script that doesn’t need to be loaded all the time. By the way, the WP-Rocket plugin has a similar option called Delay Javascript Execution. It works slightly differently and is based on any user interaction on the site, not a specific interaction you can define.

Thanks to Alligator.io

Roee Yossef
Roee Yossef

I develop custom WordPress themes by design. I love typography, colors & everything between, and aim to provide high performance, seo optimized websites with a clean & semantic code.

0 Comments...

Leave a Comment

Add code using the buttons below. For example, to add PHP click the PHP button & add the code inside the shortcode. Typo? Please let us know...