- Kentico Xperience 13
Load a site Javascript file after a Page builder is loaded in Kentico Xperience 13
In this post, I will provide you with code that loads a site JavaScript file after the Page Builder has loaded in Kentico Xperience 13.
The Problem
On my sites, I usually place a JavaScript file that handles all client-side logic right before the closing </body>
tag. In Kentico Xperience 13, I would add this to the main _Layout.cshtml
file.
On the live site, this approach works well. Unfortunately, in the Page Builder, the script file gets loaded before the widgets. As a result, the script is not applied to the markup generated by the widgets. Additionally, the widgets load after the window.onload
event, meaning there is no JavaScript event to listen for that allows you to dynamically add the script file.
I also asked Kentico support if there was a Kentico or .NET way to achieve this goal. They informed me that there isn't. So, I looked for a solution on my own.
The Solution
I ended up loading the JavaScript file using an interval to check for the existence of the .ktc-widget-zone
element. Once the element is available, the script is added to the page. If a page does not contain widgets, the script is added after a certain number of interval runs.
Add this to your main layout file (i.e., _Layout.cshtml
):
About the author
Milan Lund is a Freelance Web Developer with Kentico Expertise. He specializes in building and maintaining websites in Xperience by Kentico. Milan writes articles based on his project experiences to assist both his future self and other developers.
Find out more![Milan Lund](/_next/image?url=%2Fimg%2Fme.jpg&w=1920&q=75)