Add Loader for Shiny R

Deepanshu Bhalla 1 Comment
This tutorial covers how you can add beautiful loader in R shiny app. It includes 10 types of CSS animated loaders and animated image (GIF) which you can include in your app for better user experience.
What's Loader and What's the use of it?
You must have seen Welcome Screen when Windows 10 starts. There is a circle shaped loader which appears in Windows Screen when windows loads. It stays visible until the content or task is completed. It is very useful when you want to tell user that processing is going on behind the screen and it will be completed very soon. It is used when calculation in your dashboard is computationally intensive and it takes some time to process it. Suppose you are showing some data in a table or graph. It takes a few seconds to build the table or graph. In that case, you can show animated loader during waiting time. In R, there is a package named shinycssloaders which has various kinds of loaders along with options to customize size and color. See the different types in the GIF shown below.
css loader shiny
Sample Shiny Code
  1. Make sure you install and load shinycssloaders package before using the program below
  2. To show loader, we need to add withSpinner(tableOutput('tb'), type = 2). Here we specify the UI element for which we are adding loader. It can be tableOutput, dataTableOutput, plotOutput or plotlyOutput. type= refers to type of loader. Refer the image below for loader type you want to include.
  3. You can style spinner using options(spinner.color="#0275D8", spinner.color.background="#ffffff", spinner.size=2)
library(shiny)
library(shinycssloaders)

# Options for Spinner
options(spinner.color="#0275D8", spinner.color.background="#ffffff", spinner.size=2)

ui <- fluidPage(
             fluidRow(
               column(width=12,
                        withSpinner(tableOutput('tb'), type = 2)
               ))
)

server <- function(input, output,session) {

  output$tb <- renderTable({
      Sys.sleep(3) # system sleeping for 3 seconds for demo purpose
      iris[1:5,]
    })
  }

runApp(list(ui = ui, server = server), launch.browser = TRUE)
Important Note : For spinner type 2 and 3, it is required to include background color of the spinner using spinner.color.background="#ffffff"

Add Animated Image (GIF) as loader

To add WOW factor in your app, you can include animated image which would help to engage users on dashboard. With the use of CSS and Javascript, we can do it with ease. Refer the output shown below.
library(shiny)
library(shinydashboard)

# Running Dog
img <- 'http://northerntechmap.com/assets/img/loading-dog.gif'

# Image Size
imgsize <- "auto 40%"

# User Interface
ui <-
  dashboardPage(skin = "black",
    dashboardHeader(title = "Loading Screen"),
    dashboardSidebar(),
    dashboardBody(

# Javasript Code
singleton(tags$head(HTML("
<script type='text/javascript'>

/* When recalculating starts, show loading screen */
$(document).on('shiny:recalculating', function(event) {
$('div#divLoading').addClass('show');
});

/* When new value or error comes in, hide loading screen */
$(document).on('shiny:value shiny:error', function(event) {
$('div#divLoading').removeClass('show');
});

</script>"))),

# CSS Code
singleton(tags$head(HTML(paste0("
<style type='text/css'>
#divLoading
{
  display : none;
  }
  #divLoading.show
  {
  display : block;
  position : fixed;
  z-index: 100;
  background-image : url('",img,"');
  background-size:", imgsize, ";
  background-repeat : no-repeat;
  background-position : center;
  left : 0;
  bottom : 0;
  right : 0;
  top : 0;
  }
  #loadinggif.show
  {
  left : 50%;
  top : 50%;
  position : absolute;
  z-index : 101;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
  width: 100%;
  margin-left : -16px;
  margin-top : -16px;
  }
  div.content {
  width : 1000px;
  height : 1000px;
  }
  
</style>")))),
      
      # HTML Code   
      
      box(tags$body(HTML("<div id='divLoading'> </div>")),
          plotOutput('plot', width = "800px", height = "450px"),
          actionButton('goPlot', 'Generate Plot', icon("paper-plane"), 
                       style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),
          width = 12, height = 500)
      
      ))

  server <- function(input, output) {
  output$plot <- renderPlot({
  input$goPlot
  Sys.sleep(3)
  plot(iris$Sepal.Length, iris$Petal.Length)
  })
}

runApp(list(ui = ui, server = server), launch.browser =T)

In imgsize, the one-value sets the width of the image and height becomes "auto". For example, imgsize <- "40%" means 40% width of the image and height becomes "auto".The two-value syntax (first value: width , second value: height) imgsize <- "50% 50%". You can also use imgsize <- "auto".

Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 1 Response to "Add Loader for Shiny R"
Next → ← Prev