When it comes to integrating JavaScript
into Shiny's ui.R
, I typically use the following approach:
tags$body(tags$script(src="someJs.js"))
Within my someJs.js
file, there is a function defined like this:
function someFunc1() {
....;
}
... additional code ...
console.log(variable1);
Interestingly, the console.log
statement appears to be placed outside of the someFunc1()
function. But when I launch the App and check the console, I'm greeted with an error message stating
console.log() is not a function.
Why might this be happening?
In addition, I also include d3
in the header using
tags$head(tags$script(src="d3.v3.min.js"))
.
Unfortunately, trying to utilize d3.select...
in the console leads to another error message:
d3 is not a function.
Despite this, I rely on d3
for styling purposes within my app.
It has me wondering: How does Shiny
handle these js
files? Is there a specific object where everything gets attached to?! Sometimes it feels mysterious.
For instance, here is an easy-to-reproduce example:
ui.R
library(shiny)
shinyUI(fluidPage(
tags$head(tags$script(src="https://d3js.org/d3.v3.min.js")),
tags$head(tags$script(src="test.js")),
mainPanel(
tags$div(id = "test", "test test test")
)
)
)
server.R
library(shiny)
shinyServer(function(input, output) {
})
To replicate this, create a folder called www
alongside your server.R
and ui.R
files. Save a JavaScript file named test.js
within this folder, containing the following content:
console.log("This will cause an issue")
Now, open the browser console and you'll likely see the message:
console.log() is not a function
Feel free to try typing d3
into the console as well, which may result in:
d3 is not a function.