Here is a basic explanation in simple words.
Assuming you want to add the file myScript.js
located in c:/javascript_files
. The simplest solution would be to copy myScript.js
to a www
subdirectory where your app is located. Anything located in www
can be accessed by the UI
of your app by using the prefix /
.
For this example to add your script to the UI
you can use
tags$head(tags$script(src="myScript.js")))
The HTML code generated by Shiny is going to be
<script src="myScript.js"></script>
Your browser is going to interpret it as http://your_site/myScript.js
. Here the prefix is just /
.
But in the case you want to keep your JS code in the original location (c:/javascript_files
), you need to make it accessible to the UI
(front-end) of your app. Since you can not use a URL like http://your_site/c:/javascript_files/myScript.js
, you need to create a "virtual" subdirectory that is mapping your local directory to a URL directory, that is actually the prefix parameter in addResourcePath()
.
For this example, lets use as prefix jscode
. The expression:
addResourcePath("jscode", "c:/javascript_files")
is going to create a "virtual" directory named jscode
to be used in the URL of your app for the local directory c:/javascript_files
.
The expression:
tags$head(tags$script(src="jscode/myScript.js")))
is going to be translated to HTML as
<script src="jscode/myScript.js"></script>
which is going to be interpreted by the browser as http://your_site/jscode/myScript.js
.
If you had a subdirectory like c:/javascript_files/code_a
, you don't need to add it, you can reference it in the same way like:
<script src="jscode/code_a/myScript.js"></script>
The Shiny code to add the myScript.js
file will be:
library(shiny)
addResourcePath("jscode", "c:/javascript_files")
ui <- fluidPage(
tags$head(tags$script(src = "jscode/myScript.js"))
)
server <- function(input, output, session) {
}
shinyApp(ui, server)