Improve resources loading (CSS file)

I’m trying to improve loading of resources, specifically a CSS file within my addon. Currently I inject a CSS file via manifest.json and content_scripts with css. When the addon is applied to the target website, you can shortly see the unstyled content (FOUC), until my CSS-file has fully loaded. This can be annoying, as the elements on the target page might jump around a bit until everything is loaded.

Whether I change run_at to document_end or document_start in the manifest.json does not help. I have also tried to inject the CSS via a background-script, which loads CSS into the target-tab via browser.tabs.insertCSS. This does not seem to fully work around the FOUC problem as well.

Is there some other technique that I can try to improve loading of CSS (and maybe other resources), or is this to be expected?

Are you sure? I would guess even with a run_at: "document_end" it should still work.

I was facing this problem when I was trying to avoid black/white flash when loading my addon page in light/dark mode. And what I do is wait for the DOM to be loaded and then apply inline style based on the value stored in the “window.localStorage” (because it’s synchronous).

And in my other addon I use browser.contentScripts.register to register custom CSS style with runAt: 'document_start' and it always loads perfectly. Unlike Chrome where the flash sometimes happens because it’s missing that API and loading value from storage may not be fast enough (I can’t use localStorage there).

Also other addons like “Dark Reader” seems to work as pages are loading in dark mode without a white flash (which should be present). Note that I use also black blank page in userChrome.css (#tabbrowser-tabpanels { background-color: #000000 !important; }) so the transition is always black.

Anyway, you can experiment by loading the style using javascript.
Something like:

const styleNode = document.createElement('style');
document.head.appendChild(style);
const styleSheet = style.sheet;
styleSheet.insertRule(`body { background: yellow; }`);

If you execute it in the DOM loaded event handler, it should be applied before it gets displayed.