Step-by-Step Guide: Estimated Reading Time in Bear Blog

I'll be very short for those who just clicked this title and want results.

To show the estimated number of minutes it takes to read a blog post, add the following script to the footer directive of your Bear blog:

<script src="https://cdn.jsdelivr.net/gh/froodooo/bear-plugins@0.0.26/bear/reading-time.js"></script>

This shows the estimated reading time just below the post date, using 255 words per minute as an average reading speed. The placement and reading speed can be changed by adding the following data attributes to the script:

For example, to put the estimated reading time above the post date and set an average reading speed of 200 words per minute, use the following script:

<script src="https://cdn.jsdelivr.net/gh/froodooo/bear-plugins@0.0.26/bear/reading-time.js" data-before-child="3" data-wpm="200"></script>

There you go, enjoy!

The code

For those who are interested, this is the full script that called in the custom footer directive of a Bear blog:

if (document.querySelector("body").classList.contains("post")) {
  const readingTime = Math.ceil(document.querySelector("main").innerText.trim().split(/\s+/).length / parseInt(document.currentScript.getAttribute("data-wpm") ?? 255));
          document.createElement("p"), {
          className: "reading-time",
          innerHTML: `Reading time: ${readingTime} minute${readingTime > 1 ? "s" : ""}`
      document.querySelector("main").childNodes[parseInt(document.currentScript.getAttribute("data-before-child") ?? 4)]);

The first line makes sure that this code is only executed on blog post pages. Then, the average reading time in minutes is calculated by counting the words in the blog post (by splitting on the whitespace between words). The resulting value is rounded up. Then finally, a new paragraph is inserted on the page as a child of the tag with id main. A ternary operation makes sure that there is no "s" behind the word "minute" if the reading time is equal to 1 minute.