View plugin coordsAtPos not accurate on first load

I have a view plugin that displays little icons to the left of certain paragraphs, but if I clear my browser cache (Chrome/Windows) and reload the page (which autoloads the document into the editor), my icons are initially displayed a bit high (they use absolution positions). They are supposed to be a just left of their associated paragraph, and I get the position using a DOM getBoundingClientRect() call. I did initially call the PM coordsAtPos, with the same results.

But when I click in the editor, the plugin gets called again and the icons jump to position properly. Note that if I reload the page without clearing the browser cache, they also all are positioned correctly immediately.

I am wondering if I somehow need to make sure the dom with css is loaded and all plugins have run and updated the screen (like a decorations plugin I have that inserts html in the doc) and then somehow force the icon plugin to be run? I do call the view focus() on load, but perhaps the plugin is being called prior to the dom being drawn in the browser? Is this just a timing issue?

You probably have fonts or style sheets that are loading after the editor is initialized, changing the layout of the document.

I am loading other js and css files (and google fonts) in the section, but obviously something is not completed at the time the editor is being initialized. What might the best strategy be, to delay maybe 100ms before loading the editor? A slight delay would be of no consequence in the bigger scheme of things.

Yes, this is most likely a layout issue, not a bug in ProseMirror. Fonts and late CSS will change the height of lines, so coordsAtPos / getBoundingClientRect() are correct for now, but not yet. That becomes clear when you clear the cache.

Don’t set a random timeout. Instead, start a recompute when the layout is stable:

Wait for the fonts to load (document.fonts.ready).

or use ResizeObserver on the editor DOM to see how the size changes.

or make a plugin update happen through a transaction after everything has loaded

The fact that a click fixes it is a sign that any change in state forces a redraw and recalculates coords. If you hook into that moment directly, you’ll be fine.

Thanks, zooha, my problem was likely that the DOM itself was not yet updated upon initial editor load and plugin execution (the decorations were probably not yet put into the DOM), so to make it work I just do a re-run of the view (using a plugin key) that relies on those decorations after the editor is loaded and the dispatch event for the decorations has been run.