On most pages, I see two or three separate visible layout reflows:
Mobile mode: https://en.m.wikipedia.org/wiki/Kahlúa
1. Initial rendering with page title, first paragraph, infobox, first thumbnail. The first section (e.g. "History") is naturally rendered below that.
2. Table of contents and first section disappear leaving a blank space. mobile-toc is rendered below-the-fold (it clears the float which means it renders below the infobox and thumb).
Desktop mode: https://en.wikipedia.org/wiki/Kahlúa?useskin=minerva
1. Initial rendering with page title, first paragraph, infobox, first thumbnail. The table of contents and first section (e.g. "History") are naturally rendered below that.
2. Table of contents and first section disappear leaving a blank space. mobile-toc renders below-the-gold. While I don't always see it, recording the timeline in Chrome shows that the browser had to perform two additional reflows directly after this (caused by clear-float insertion).
This is caused by the operations being performed on the live document (instead hooking in to the initial rendering), and in multiple steps.
The code should be simplified to perform a single atomic change (instead of two or three). E.g. use `replaceWith` instead of `remove`+`append`, or perform one `append()` (making a fragment containing two elements), instead of two separate append calls.
Also remember styles like `.client-js .toc { display: none; }` would help to ensure the browser never renders the (unwanted) default TOC to begin with.
Injecting `<div style="clear:both;"></div>` with javascript also causes extra reflows. As it first renders the content with new TOC around it, and then again with a clear in between. These elements can be inserted in one operation instead of two (or better, use specify the float-clear in the stylesheet without an extra element).
Related:
* https://gerrit.wikimedia.org/r/#/c/143062/6/javascripts/modules/toc/toc.js