Site icon Hip-Hop Website Design and Development

How can I make sure my JS script gets executed first, among other scripts?

I have this script that cuts down my menu and adds a “+” dropdown if there are too many menu items in an attempt to prettify long menus, as such:

Without the script running:

Which I call in functions.php with:

function _s_scripts() {
    wp_enqueue_script( 'main', get_template_directory_uri() . '/js/main_res.js', array( 'jquery' ), '', false );
}
add_action( 'wp_enqueue_scripts', '_s_scripts' );

Unfortunately, this results in late-execution and jagginess. Is there any way I can hook this script into “as soon as you’re done generating X part (menu)” do this?

The effect is very noticeable for the user:

https://imgur.com/aoFcYKe

and here’s the script, just for testing purposes, main_res.js:

function sliceMenu(desired_len) {
    var menu_len = document.querySelectorAll('#primary-menu > li').length;

    if (menu_len > desired_len) {

        var append_menu_el = document.createElement('div');
        append_menu_el.innerHTML = ('<div id="js-cover-menu"><img class="plus" src="$PATH/svg/plus_menu.svg" alt="more-menu"></div>').replace('$PATH', ABSPATH);
        document.getElementById('primary-menu').parentNode.appendChild(append_menu_el);

        let diff = menu_len - desired_len;
        let sliced_lis = [...(document.querySelectorAll('#primary-menu > li'))].slice(-diff);


        var js_menu_el = document.createElement('ul');
        js_menu_el.setAttribute('id', 'js-cover-menu-dropdown');
        document.getElementById('js-cover-menu').appendChild(js_menu_el);

        js_cover_menu_el = document.getElementById('js-cover-menu-dropdown');

        for(var i = 0, length = sliced_lis.length; i < length; i++) {
            js_cover_menu_el.appendChild(sliced_lis[i]);
        }
        document.querySelectorAll('#js-cover-menu-dropdown > li > ul').forEach(node => node.remove());
    } else {
        return;
    }
}