AlexRos
AlexRos

Reputation: 13

Call javascript function on page load in R shiny

I added references to css and javascript files as follows:

  tags$link(rel="stylesheet", type="text/css", href="rtp.css"),
  tags$script(type="text/javascript", src = "rtp.js"),

How do I make a call to a javascript function defined in "rtp.js"? I have tried

tags$script(type="text/javascript", src = "myfunction()")

(which does not work).

Upvotes: 1

Views: 2715

Answers (2)

GGamba
GGamba

Reputation: 13680

You can use the JS() function from htmlwidgets package (I think it comes by default with shiny)

To add a custom function executing at the start of the application:

tags$script(JS('alert("initialized!")'))

tags$script(JS('myfunction()'))

If myfunction() resides in an external file, first import it and the execute:

tags$script(type="text/javascript", src = "rtp.js"),
tags$script(JS('myfunction())'))

Upvotes: 2

Hong Ooi
Hong Ooi

Reputation: 57686

The src="foo" argument means to get the source for your script from a file named foo. If you have inline code instead, then provide an unnamed argument to tags$script:

tags$script(type="text/javascript", "myfunction()")

# <script type="text/javascript">myfunction()</script>

Upvotes: 1

Related Questions