Milan Lund logo

Hi, I am Milan Lund!Freelance Web Developer with Kentico Expertise

I specialize in building and maintaining websites on the Kentico platform.

  • 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 a code that loads a site Javascript file after a Page builder is loaded in Kentico Xperience 13.

Problem

In my sites, I usually put a Javascript file that performs all of the client-side logic right before the closing body tag. Considering Kentico Xperience, I would add it to the main _Layout.cshtml file. 

Loading...

On the live site, that works well. Regrettably, in the Page builder, the script file gets loaded before the widgets. So, the script is not applied to the markup that is generated by widgets. Moreover, the widgets load after the window.onload event, and therefore there is no Javascript event you can be listening to be able to add the script file dynamically.

I also asked Kentico support, whether there is a Kentico or a .NET way to achieve the goal. I was told there is nothing like it. So, I was looking for a solution on my own.

Solution

I ended up loading the Javascript file using an interval checking 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 amount of interval runs.

Add this in your main layout file (i.e. _Layout.cshtml):

Loading...


About the author

Milan Lund is a freelance web developer with expertise in Kentico. He specializes in building and maintaining websites on the Kentico platform. Milan writes articles based on his project experiences to assist both his future self and other developers.

Find out more
Milan Lund