Frontend
Theme JS

Adding External Javascript

4min

Klevu adds external Javascript files to your site to enable Klevu Theme JS to work as expected. The core file is always added when any Klevu solution is enabled. Other files include Recommendations, Category Navigation, SRLP and Quick Search.

Javascript required at load time

The majority of the files added by Klevu are required at load time and are added to the head via the Magento secureRenderer like so.

module-m2-frontend/view/frontend/templates/html/head/js_includes.phtml


Javascript that can be deferred

Quick Search however is not required at load time and can be loaded after page load.

We have taken a lead from Hyvä Themes with our approach here adding files to the head after load to avoid blocking the rendering of the page. e.g.

JS


Our implementation can be found in this template file

module-m2-frontend/view/frontend/templates/html/head/js_includes_defer.phtml


We loop through all provided links and add them to the head after page load.

Adding scripts to the head in this manner is better for performance however, it does not add those scripts via secureRenderer. External scripts added from klevu.com are whitelisted via etc/csp_whitelist.xml in the relevant modules.

Note: All Klevu scripts are removed from the checkout page by default.

If you require those scripts to be added via the secureRenderer please ensure you inject quick search to the head using the first method.

Layout XML to make that switch:

Vendor/Magento/view/frontend/layout/default.xml


The example given shows how to make this change in a module. Theses change could alternatively be made in your theme(s).