Topic on Talk:Snippets/Auto-number headings

Matěj Suchánek (talkcontribs)

@Krinkle: Thanks for this script. Based on a user's request, I was wondering how to make it work when the page content updates dynamically. mw.hook( 'wikipage.content' ).add( ... ) is a native way to do it, but I notice your snippet does not use jQuery (on purpose?).

Krinkle (talkcontribs)

@Matěj Suchánek Good question!

Using the hook would result in bugs that I'm not sure how to avoid, for so I felt it was cleaner to leave that part out. For the simple case of a full-page render, such as previewing a source edit, or post-edit when using VisualEditor, we could re-select the TOC and perform otherwise the same logic. However, the wikipage.content is not specific to a full-page render, it can also be applied to portions of content, or content without a TOC. This would lead to a situation where we've already inserted some numbers but then are given the impossible task of adding numbers to only part of a page, possibly without a TOC that time.


My suggestion would be to use the CSS version of the snippet instead. That should work automatically in every context, including dynamic updates that re-render all or some of the page in any way imaginable. To do this, reduce the JS snippet to only the "else" branch where the body class is set. This does not require a hook. The downside, as documented in the CSS snippet, is that this may in some cases result in headings that have different numbers than the TOC.

Matěj Suchánek (talkcontribs)

Thanks for your answer. Now there is an interesting actuality. When I was writing my question in 2022, we didn't have the new vector-2022. In vector-2022, TOC doesn't have numbers and document.querySelector('#toc') refers to nothing, so CSS is basically the only useful part in that skin.

Reply to "Dynamic execution"