Remove flickering flash messages on Turbolinks

If you're using Turbolinks, and flash messages in your Rails app, then this might come in handy.

You might have seen flickering flash messages on your pages when you re-visit them in your app. This is because Turbolinks caches the full page content in its own internal cache. And this cache includes your flash message if you don't explicitly take it out.

Thus, when you revisit a page where a flash message was just displayed, you first see that cached page for an instance. Then the flash messages dissapears because Turbolinks asynchronously loads your actual page content via AJAX.

Here's a snippet we're using to take any flash messages out of the page before sending it to the Turbolinks cache:

document.addEventListener("turbolinks:before-cache", function() {
   const flash_message_element = document.querySelector(".flash")
   if (flash_message_element) {
Remove flash message before sending to Turbolinks cache

Show Comments