Go to main content

Load a site Javascript file after a Page builder is loaded in Kentico Xperience

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.

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. 

    ...
    <script src="/Content/script.js" async asp-append-version="true"></script>
</body>
</html>

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):

@if (Context.Kentico().PageBuilder().EditMode)
    {
        <script>
            window.addEventListener('load', function () {
                var ktcCounter = 0; // Interval counter for pages that do not have widget zones
                var interval = setInterval(function () { // Start interval with 200ms timer
                    var ktcElem = document.querySelector('.ktc-widget-zone'); // Try to get a widget zone element
                    if (ktcElem || ktcCounter > 10) { // If a widget zone is available or an interval counter exceeds a treshold
                        var body = document.querySelector('body');
                        var script = document.createElement('script'); // Create a script tag
                        script.type = 'text/javascript';
                        script.src = '/Content/script.js?v=' + (new Date()).getTime(); // Always get a fresh JS file
                        body.appendChild(script); // Add the script tag in the page
                        clearInterval(interval); // Stop the interval
                    }
                    ktcCounter++;
                }, 200);
            });
        </script>
    }
    else
    {
        <script src="~/Content/script.js" async></script>
    }


Further reading

all posts