Un-FOUC your m3 dependency

If your app uses the M3 Theme dependency, you’ve may have seen UI elements briefly flash their default Anvil style before switching to M3, especially the m3 icons. This is apparently a common issue in web development called FOUC (flash of unstyled content).

Here’s a simple fix:

  1. Hide the body early (when not in the designer view!). In Native Libraries, add:
<script>
  if (!window.anvilInDesigner) {
    document.head.insertAdjacentHTML('beforeend',
                                     '<style id="fouc-that">body { opacity: 0; transition: opacity 0.15s ease-in; }</style>'
                                    );
  }
</script>
  1. Reveal it after your startup form opens:
import anvil.js
def _reveal_body() -> None:    
  anvil.js.call_js("setTimeout", 
    lambda: anvil.js.call_js( 
      "eval", 
      "var g = document.getElementById('fouc-that'); if(g) g.remove();", 
    ),  
    50, 
  )

Call _reveal_body() after every open_form() in your startup flow. The 50ms buffer ensures any dynamically injected CSS (late-loaded overrides etc.) has applied before the page becomes visible.

5 Likes

Nice. You can do that whole function in python if you want.

from anvil.js.window import setTimeout, document

def handle_reveal():
    el = document.getElementById("fouc-that")
    if el:
        el.remove()
    

def _reveal_body() -> None:    
   setTimeout(handle_reveal, 50)
5 Likes