Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a remote JavaScript file in a shiny dashboard app?

How can I include a remote JS file in my app using shinydashboard? I know there is the includeScript function. I tried

...

# using shiny dashboard
ui <- dashboardPage(

  includeScript("http://the.path.to/my/js-file.js")

  dashboardHeader(
    title = "My title",
    titleWidth = 400
  ),

...

This results in the error:

Error in tagAssert(header, type = "header", class = "main-header") : 
Expected tag to be of type header

I attempted to place the call in other places, combine it with tags$head, store the JS file locally and load it with a local path reference, but to no avail.

So I am stuck at the following questions?

  1. Can I actually use includeScript with a path to a remote resource?
  2. Where do I need to put which instruction to load the JS file (and where does the JS file need to reside)?

A solution has been proposed by @daattali for a purely Shiny based implementation (no shinydashboard) using tags$head, but this does not appear to work with shinydashboard.

like image 961
matt_jay Avatar asked Dec 09 '22 01:12

matt_jay


1 Answers

You can include remote JS files using the src argument of a script tag

library(shiny)
jsfile <- "https://gist.githack.com/daattali/7519b627cb9a3c5cebcb/raw/91e8c041d8fe4010c01fe974c6a35d6dd465f92f/jstest.js"

runApp(shinyApp(
  ui = fluidPage(
    tags$head(tags$script(src = jsfile))
  ),
  server = function(input, output) {
  }
))

EDIT: Ok, so you want this to work with a shinydashboard. It makes sense why your way doesn't work. Look at the documentation for dashboardPage. The first argument is header. You can't just start providing tags/UI elements you want to include. The includescript or any other such elements should go inside the dashboardBody. For example

library(shiny)
library(shinydashboard)
jsfile <- "https://gist.githack.com/daattali/7519b627cb9a3c5cebcb/raw/91e8c041d8fe4010c01fe974c6a35d6dd465f92f/jstest.js"

runApp(shinyApp(
  ui = dashboardPage(
    header = dashboardHeader(),
    sidebar = dashboardSidebar(),
    body = dashboardBody(
      tags$head(tags$script(src = jsfile))
    )
  ),
  server = function(input, output) {
  }
))
like image 166
DeanAttali Avatar answered Feb 13 '23 10:02

DeanAttali