Ghost Theme: Add Reading Time to Your Blog

Whilst embarking on my mission to create a my first Ghost theme, I took inspiration from other popular blogs and borrowed ideas that I liked or thought worked well (a standard way of helping you design if you don't have a natural 'knack' for it; fake it before you make it!).

I'm a big fan of Medium as a platform for reading, although not as a blog hosting platform but we'll leave that debate for another day. It provides a crisp, clean design that removes many barriers and distractions from the reader and gives the user slimmed down features that only enhance the reading pleasure.

One such feature that I admire is the reading time feature. By providing the reader with an up-front estimate of how long it will take to read an article they can know whether they have the time to read it. Personally, I believe this can entice readers who might otherwise have abandoned reading a slightly longer article.

How to add Reading Time to your blog

To add reading time I simply did the following:

  • Added a reading-time anchor tag in the post.hbs file
  • Added JavaScript that read the contents of the post and calculated reading time by using the average reading speed.

In order to style the reading time element we just need a placeholder div for it...

<div class="reading-time"></div>

We need to import the Js at the top of our theme:

<script async src="{{asset "js/min/reading-time.min.js" }}"></script>

If you've noticed we declare async since we want to load the Js file asynchronously from it's source but it can load slightly later without it being too big a deal.

Javascript for Calculation

To calculate the reading time we use javascript. This assumes that the average word reading count for adults is 250 words per minute. We grab our content from the content div.

Our word count is calculated by firstly replacing all non-word characters e.g. (anything that's not a-z A-Z 0-9) then splitting on each whitespace character. We then divide the number of words by the average word count then round up the nearest whole minute.

Finally, we set the value of the reading-time text to the result of our previous code.

$(document).ready(function() {
    var txt = $('.content')[0].textContent,
    wordCount = txt.replace( /[^\w ]/g, "" ).split( /\s+/ ).length;

    var readingTimeInMinutes = Math.floor(wordCount / 250) + 1;
    var readingTimeAsString = readingTimeInMinutes + " min";
    $('article .reading-time').html(readingTimeAsString);

Hope you enjoyed this tutorial. I'll do my best to add more around configuring your Ghost theme. One also about writing an entire Ghost theme from scratch.

James Murphy

Java dev by day, entrepreneur by night. James has 10+ years experience working with some of the largest UK businesses ranging from the BBC, to The Hut Group finally finding a home at Rentalcars.

Manchester, UK
comments powered by Disqus