`singleton()` usage in Shiny UI

I'm a bit confused about the usage of htmltools::singleton(). In a toy Shiny app, I've created this UI:

ui <- fluidPage(
  singleton(tags$head(tags$script(src = "foo"))),
  tags$head(
    tags$script(src = "foo")
  ),
  tags$script(src = "foo")
)

In the rendered page, all three <script> tags appear; I'd have expected at most two (where the second <script> tag in the <head> is omitted).

This version results in all three tags, too:

ui <- fluidPage(
  tags$head(
    singleton(tags$script(src = "foo")),
    tags$script(src = "foo")
  ),
  tags$script(src = "foo")
)

I've used HTML dependencies before to abstract-away this issue, but here I'd like to use singleton() directly and obviously I'm doing something wrong :-/
Can anyone point me to some working examples of singleton()? (I started to read the unit tests within {htmltools} directly, but I figured to ask the community before heading down that rabbit-hole :-).)

It seems each tag needs to be wrapped in singleton() for this to work as expected:

library(shiny)
library(htmltools)

ui <- fluidPage(
  singleton(tags$p("test")),
  singleton(tags$p("test")),
  singleton(tags$p("test"))
)

server <- function(input, output, session) {}

shinyApp(ui, server)

After some more experimenting, it seems the 'unique' key is simply the argument to singleton() (and not any DOM context while actually assembling the HTML of that argument), as this results in only a single script tag (in this case, in the <body>, not the <head>, as the former appears first in the R-handling (though second in the rendered HTML)):

ui <- fluidPage(
  singleton(tags$script(src = "foo")),
  tags$head(singleton(tags$script(src = "foo")))
)

This topic was automatically closed 7 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.