facetwp conditionally change templates

<?php
/** Conditionally change templates on AJAX refresh, only works for use with FacetWP
 ** listing builder templates
 **/
add_action( 'wp_footer', function() {
	?>
    <script>
        (function($) {
            $(document).on('facetwp-refresh', function() {
                if ( 'undefined' !== typeof FWP.facets['categories'] && FWP.facets['categories'].length > 0 ) {
                    FWP.template = 'example_2';
                } else {
                    FWP.template = 'example';
                }
            });
        })(jQuery);
    </script>
	<?php
}, 100 );