Include a javascript file in Shiny app

What you need to do is:

  1. create www folder in the same folder as server.R and ui.R
  2. put javascript file into www folder.
  3. put tags$head(tags$script(src="https://stackoverflow.com/questions/23599268/hoge.js")) in UI.

The folder looks like:

├── server.R
├── ui.R
└── www
    └── hoge.js

The ui.R is something like

library(shiny)
shinyUI(pageWithSidebar(
  headerPanel("New Application"),
  sidebarPanel(
    sliderInput("obs", 
                "Number of observations:", 
                min = 1, 
                max = 1000, 
                value = 500)
  ),
  mainPanel(
    plotOutput("distPlot"),
    tags$head(tags$script(src="https://stackoverflow.com/questions/23599268/hoge.js"))
  )
))

and server.R

library(shiny)
shinyServer(function(input, output) {
  output$distPlot <- renderPlot({
    dist <- rnorm(input$obs)
    hist(dist)
  })
})

Note that these are templates generated by Rstudio.

Now head of html looks like:

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  ... snip ...
  <script src="https://stackoverflow.com/questions/23599268/shared/slider/js/jquery.slider.min.js"></script>
  <script src="https://stackoverflow.com/questions/23599268/hoge.js"></script>
</head>

Leave a Comment