Embedding javascript file within a shiny app www subdirectory does not work

Seems like shiny cannot recognize my .js file. Question is why?

Inlined js script text runs smoothly:

library(shiny)

header = dashboardHeader(disable = TRUE)
sidebar = dashboardSidebar(disable = TRUE)

body = dashboardBody(
    
    shiny::tags$script(
        HTML("document.body.style.backgroundColor = 'skyblue';")),
)

ui = dashboardPage(header = header, sidebar = sidebar, body = body)

server = function(input, output, session){

}
shinyApp(ui, server)

However when i embedd my .js file (myscript.js stored within www subdirectory)

document.body.style.backgroundColor = "skyblue";

  $("firstinput").on("keypress", function(){
      alert("Pressed");
    })
  
  $(document).on('shiny:connected', function(event) {
  alert('Connected to the server'); 
    })

...like this:

library(shiny)

header = dashboardHeader(disable = TRUE)
sidebar = dashboardSidebar(disable = TRUE)

body = dashboardBody(
    
    shiny::tags$head(
        shiny::tags$script(
            src = "myscript.js"
        )),
        
        HTML('<input type="button" id="firstinput">')
)

ui = dashboardPage(header = header, sidebar = sidebar, body = body)

server = function(input, output, session){
    
}
shinyApp(ui, server)

nothing is applied... How comes?

In the second approach, you are using tags$head around the script, but not in your first approach, did you do that on purpose? Without this, it does work for me.

When you execute the current dashboardBody in the R console, you can see that the script is not set in the resulting html.

Yes i did that on purpose because i wanted to explicitly embed my .js file in the header, since i am not sure if i face some drawbacks when i do otherwise. Running the script without tags$head() works for me aswell but the .js file is placed in the body of the resulting html and not in the header.

For example when i embed other .js files such as jBox (randomly picked)

shiny::tags$head(
    shiny::tags$script(
        src = "https://cdn.jsdelivr.net/gh/StephanWagner/jBox@v1.2.0/dist/jBox.all.min.js"
    ))

and it works just fine. Strange for me that it doesnt work when i embed my own .js file.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.