How to load CSS or js files in ui.R dynamically?

shiny

#1

ui.R code like this:

#comments
a <<- read.table("xxxx")
shinyUI(fluidPage(useShinyjs(),
                  tags$head(
                    includeCSS("styles.css"),
                    includeScript(path=ifelse(a==0,path1,path2))
)
))

when i change the global variable a,the ui take not affect, unless i modify the ui.R file ,eg. add some comments.
why ui.R file has no change,the dynamic includeScript or includeCSS have no effects,just load the CSS JS file last time you change the ui.R?
how to check this point? and how to resolve it?
thanks very much!


#2

The problem is probably that Shiny server does not re-run the ui.R file until it changes (even on browser reload), and your ifelse statement needs execution to happen. If you're on Linux you can run touch on ui.R to force a server reload:

system("touch ui.R")

#3

@stkrog is right that the ui.R file is re-run only when the file changes.

Another way to make it re-run the code every time a new user session starts is to make the UI a function. You essentially just wrap your code in a function that returns the content, like this:

function(req) {
  a <<- read.table("xxxx")
  fluidPage(useShinyjs(),
    tags$head(
      includeCSS("styles.css"),
      includeScript(path=ifelse(a==0,path1,path2))
    )
  )
}

The function will run each time someone connects, which will do what you want. Note that there is a performance cost to doing this, since it runs the UI code every time. In many cases, the performance cost is negligible, and it may be worth it in your case.


#4

thank you very much!!
what's meaning the parameter "req" for the function?


#5

req is an object that represents the HTTP request. Some applications might want to customize the UI based on the request, although it is rare. For your purposes, you're always doing the same thing, so you don't need to look at req.


#6

it's ok,you are my hero,tanks very much!