EDIT: This blog post has been edited and published to the REQ blog (where I work). Head over there for a more up to date version of this!

Original article:

I’m gonna keep this short and sweet. After much research, I was unable to find a library or solution to my page transition problem. Many of the libraries I found use pushState() and the History API, or some sort of pre-fetch, to change pages as seamlessly as possible for the user. Barba.js is a good example — but I was unable to pre-fetch meta tags, which are essential for most of the SEO work that I do. It also required a larger amount of set up and added some code-bloat that slowed down the site. While there were some fancy examples, I ultimately had to find another solution.

Well, I found a way to do it in plain old Vanilla JavaScript. From what I can tell, this is an (almost) perfect solution to page transitions. I was surprised that it worked so well without hearing of it before. Now I say almost perfect, because it has some limitations. Depending on your animation, you may see a slight flash between page loads. This is pretty much expected behavior normally, but we do really want that nice and smooth animation. We will look into a way that we can avoid that as well! For now, let’s get right into it.

Yep, that’s it. Let me break it down for you. We are essentially using setTimout() to stop the page from loading, performing our animation, and then loading the next page after whatever time you have given.

Any time a link is clicked, we first stop the load with e.preventDefault(). We then start a timer of 500 milliseconds. Right after that, we add our css class to the body. After the 500ms, we do two things: first, check if the class has been added. Then we have to check if the <a> tag is a parent element. Many times, <a> tags will wrap other elements, such as images. Why we have to do this check has to do with the click event, and how it bubbles, but that is slightly beyond the scope of this article :) Then we load the next page! How the animation works in this example is just a simple fade out and back in, using css animations.

There you have it. Page transitions in less than 30 lines of vanilla JS. Our example here is fairly simple, but it can get as complex as you would like.