Published on 04/21/2025
Published by amit
Optimizing Ubermenu/Mega Menu for CWV
Here is a quick snippet on how to optimise the mega menu for CWV and improve on TBT.
Assuming your code is like this
|
1 2 3 4 5 6 7 8 9 10 |
<div class="primary_menu is-flex justify-content-end"> [wp.menu] { "theme_location": "ubermenu_navigation", "echo":false, "walker":true } [/wp.menu] </div> |
Make the changes so that it looks something like,
|
1 2 3 4 5 6 7 8 9 10 |
<div class="primary_menu is-flex justify-content-end js-primary_ubermenu" style="height:56px"></div> <template axn=selector.update selector='.js-primary_ubermenu' get='me.html'> [wp.menu] { "theme_location": "ubermenu_navigation", "echo":false, "walker":true } [/wp.menu] </template> |
What I have changed is
- Wrapped the wp.menu shortcode within template tag,
- Closed the primary_menu div
- Added a class “js-primary-ubermenu” to the div, you can add any class as long as it is unique on the page. This class is used as the selector in the template tag
- I have added an inline style to set the height of the DIV so that CLS is not impacted.
When spa.js loads and executes, it retrieves the HTML within the template tag and inserts it into the correct location.
In case your mega menu needs to be opened on click instead of hover, put the following code
|
1 2 3 4 5 |
<script type="spa/axn" axn="core.run_script"> setTimeout(() => { $( '.ubermenu' ).ubermenu({}).trigger( 'ubermenuinit' ); }, 300); </script> |
A 300 ms delay is added to ensure that user experience, page speed, or CWV is not impacted.