在Shiny应用程序中包含一个javascript文件

Ban*_*you 34 javascript r shiny

我需要在我的Shiny应用程序中包含一个js库.目前我使用includeHTML将脚本直接包含在html代码中.例如

includeHTML('URL.js')
Run Code Online (Sandbox Code Playgroud)

当我尝试浏览js文件时,浏览器将显示"Not Found",如果我使用tags $ script,例如

http://127.0.0.1:7106/URL.js

tags$script(src = 'URL.js')
Run Code Online (Sandbox Code Playgroud)

现在我把URL.js放在ui.r和server.r的同一个文件夹中.

我应该在哪里存储URL.js文件?或者还有其他方法来包含js文件?

谢谢你的任何建议.

koh*_*ske 51

你需要做的是:

  1. 创建www在同一文件夹的文件夹server.Rui.R
  2. 把javascript文件放到www文件夹中.
  3. 放入tags$head(tags$script(src="hoge.js"))UI.

该文件夹看起来像:

??? server.R
??? ui.R
??? www
    ??? hoge.js
Run Code Online (Sandbox Code Playgroud)

ui.R是一样的东西

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="hoge.js"))
  )
))
Run Code Online (Sandbox Code Playgroud)

server.R

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

请注意,这些是Rstudio生成的模板.

现在head的html看起来像:

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  ... snip ...
  <script src="shared/slider/js/jquery.slider.min.js"></script>
  <script src="hoge.js"></script>
</head>
Run Code Online (Sandbox Code Playgroud)

  • 或者使用 `includeScript`,它接受一个参数 `path`,基本路径是 Shiny 应用程序目录。然而`includeScript` 将内联文件中的javascript。 (2认同)

Sta*_*lav 8

另一种方法是使用:

includeScript("mapManipulator.js"),
Run Code Online (Sandbox Code Playgroud)


Sat*_*ish 5

 ???shiny
    ??? server.R
    ??? ui.R
    ??? www
        ??? stylesheet.css
        ??? js
             ??? hoge.js
Run Code Online (Sandbox Code Playgroud)

用户界面

其中任何一个都可以工作

1. tags$head(HTML("<script type='text/javascript' src='js/hoge.js'></script>"))

2. HTML('<head>
              <link rel="stylesheet" type="text/css" href="stylesheet.css">
              <script type="text/javascript" src="js/hoge.js"></script>
          </head>')
Run Code Online (Sandbox Code Playgroud)