By default, Klevu’s JavaScript libraries are loaded in a render-blocking manner, as opposed to being loaded asynchronously once the page has loaded. This means that the scripts will be downloaded and will start processing before the browser starts rendering your page content.
Page speed reports, such as Google’s Core Web Vitals, may flag this as a performance bottleneck causing first paint times to be impacted. This may appear to be a concern out of context, however, for real-world users, the browser will cache the downloaded JavaScript files after the initial download, meaning what may be a few tenths of a second becomes negligible after the first page in a session.
When automated tools measure this metric, however, they must download the JavaScript files for each report, removing the benefits of browser level caching.
Additionally, by starting to process the Klevu JavaScript before all assets are loaded and the page has completed rendering, we can take advantage of the browser performing tasks in parallel. This causes Klevu solutions to be displayed and functional quicker than otherwise, leading to an overall improved user experience for your visitors.
If, given the above, you still wish to defer the loading of the Klevu JSv2 library, you may enable this via the setting under Stores > Configuration > Klevu > Search Configuration > Developer Settings > Defer Klevu JavaScript . This is a store level setting, meaning multisite installations can enable / disable on a store-by-store basis.
When enabled, all Klevu related JavaScript included with the core modules will be deferred until after page load. For included assets (such as the core JS library; SRLP functionality; etc), this is achieved using the defer=”defer” attribute. For inline scripts, such as setting initialisation values including API keys, this is achieved by pushing the code into the _klvReady stack to be picked up automatically when the Klevu libraries are available.
Before enabling this setting, please ensure you have also deferred any such modifications.
Example Deferred Inline Script
The following example sets the Klevu API key for search on the storefront
klevu({
"search": {"apiKey": "klevu-1234567890"}
});
After enabling defer, this call will fail with an error that “klevu” is not defined, as it executes as part of page render - before the core library has started downloading.
To resolve this, the call must be pushed to the _klvReady stack, where it will not be evaluated until after klevu is available
window._klvReady = window._klvReady || []; // Ensure the variable exists
window._klvReady.push(function() {
klevu({
"search": {"apiKey": "klevu-1234567890"}
});
});