Getting a Random Post in Jekyll

I really like blogging with Jekyll. It gives me all the functions I need for a simple blog without any complicated extras. Using Wordpress for a personal blog seems like trimming your nails with a saw. Every so often, I’d like to add something or another to my site that requires some creativity to implement within Jekyll.

I like random post buttons. I’d like to see our digital age use randomness to introduce new ideas to people rather than understanding their tastes and creating a filter bubble. The The Dice Man is worth pondering.

The Concept

  1. Put the URL of each post into an array.
  2. Generate a random integer bounded by 0 and the number of posts.
  3. ArrayOfPosts[randomNumber] == link to a random post

With a static blog, the only option is to do all of this with client-side JavaScript.

My first version used Liquid to set up the array on the page where the random link was. This won’t scale well, as a mature blog can easily have a thousand posts. An extra thousands lines of code on each blog post defeats the purpose of a sleek and minimal Jekyll blog. I figure only a small minority of my readers would use the random post link, yet I’d be inflicting slightly slower load times on everyone.

I got around this by making the random link go to a page that runs the client-side JavaScript and automatically redirects to the random page. I suppose at some point this could become annoying slow, but such is one of the limitations of a static site.

The Code

This is the code that makes up the entire page that the random post link leads to:

<head>
  <script>
    function randompostlink() {
    var postList = []; 
    {% for post in site.posts %}
    postList.push('{{post.url}}')
    {% endfor %}
    var randomPostLink = 
    	postList[Math.floor(Math.random() * postList.length)];
    return randomPostLink;}
  location.replace(randompostlink())
  </script>
</head>

The original code is on GitHub.

I also added a message in <noscript> tags in case a user has JavaScript disabled. The site still works without JavaScript, but I give fair warning that some extras require it.

The Payoff

If you navigate to derekkedziora.com/blog/random, you’ll automatically be redirected to a random post on my blog.

Wikipedia also has a page that redirects to a random article, although the magic works server-side. Reddit does the same trick with reddit.com/r/random. The benefit of running the code server side is that the feature still works even if someone has JavaScript turned off, besides being much faster at scale.

Have some fun and get outside your bubble with random sites!