首次执行时Shiny繁忙提示不显示的问题解决需求
解决Shiny应用首次执行不显示繁忙提示的问题
问题原因
首次启动应用时,uiOutput("busy")对应的renderUI需要等待服务器完成初始的renderPlot计算后才会渲染提示元素,但此时shiny-busy状态已经结束,导致首次执行时用户看不到繁忙提示。只有后续调整参数时,提示元素已经存在,才能正常捕捉到shiny-busy状态。
解决方案
直接在UI中嵌入繁忙提示的HTML代码,无需通过服务器端的renderUI生成。这样页面加载完成后提示元素就已存在,能立刻响应首次执行时的shiny-busy状态。
修改后的完整代码
library(shiny) # Define UI for application that draws a histogram ui <- fluidPage( # Application title titlePanel("Old Faithful Geyser Data"), # Sidebar with a slider input for number of bins sidebarLayout( sidebarPanel( sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30) ), # Show a plot of the generated distribution mainPanel( # 直接嵌入繁忙提示HTML,无需uiOutput HTML(" ", paste0( '<span data-display-if="', '$(\'html\').attr(\'class\')==\'shiny-busy\'', '">', '<i class="fa fa-spinner fa-spin-pulse fa-fw" style="color: #337ab7;" >busy</i>', '</span>' )), plotOutput("distPlot") ) ) ) # Define server logic required to draw a histogram server <- function(input, output) { output$distPlot <- renderPlot({ # generate bins based on input$bins from ui.R x <- faithful[, 2] bins <- seq(min(x), max(x), length.out = input$bins + 1) for(i in 1:10000000){# 模拟耗时计算 log(i) } # draw the histogram with the specified number of bins hist(x, breaks = bins, col = 'darkgray', border = 'white', xlab = 'Waiting time to next eruption (in mins)', main = 'Histogram of waiting times') }) } # Run the application shinyApp(ui = ui, server = server)
关键修改点
- 移除了服务器端的
shiny_busy函数和output$busy的renderUI逻辑 - 将原
shiny_busy()生成的HTML代码直接写入UI的mainPanel中,确保页面加载时提示元素已存在,能及时响应首次的shiny-busy状态
内容的提问来源于stack exchange,提问作者Steven Ouellette
相关产品推荐
相关产品推荐

