How to make a table of content at the top of page?

Ideally, it should be a programmable approach, for example, allow such table of content to be made automatically when the page length is longer than certain configurable threshold.
