search ]

Optimize Performance with Lazy Loading for JavaScript

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 pixel-perfect custom WordPress themes, delivering high-performance, SEO-optimized websites. Have a project in mind? need assistance? Feel free to contact me!

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!