ui.include_js

ui.include_js(path, *, method='link', **kwargs)

Include a JavaScript file.

Parameters

path : Path | str

A path to a JS file.

method : Literal[‘link’, ‘link_files’, ‘inline’] = 'link'

One of the following: * "link" is the link to the JS file via a script tag. This method is generally preferable to "inline" since it allows the browser to cache the file. * "link_files" is the same as "link", but also allow for the JS file to request other files within path‘s immediate parent directory (e.g., import another file). Note that this isn’t the default behavior because you should be careful not to include files in the same directory as path that contain sensitive information. A good general rule of thumb to follow is to have path be located in a subdirectory of the app directory. For example, if the app’s source is located at /app/app.py, then path should be somewhere like /app/js/custom.js (and all the other relevant accompanying ’safe’ files should be located under /app/css/). * "inline" is the inline the JS file contents within a script tag.

****kwargs** : TagAttrValue = {}

Attributes which are passed on to ~shiny.ui.tags.script.

Returns

: Tag

A script tag.

Note

This places a script tag in the body of the document. If you want to place the tag in the head of the document instead, you can wrap it in head_content (in this case, just make sure you’re aware that the DOM probably won’t be ready when the script is executed).

ui.page_fluid(
    ui.head_content(ui.include_js("custom.js")),
)

# Alternately you can inline Javscript by changing the method.
ui.page_fluid(
    ui.head_content(ui.include_js("custom.js", method = "inline")),
)

See Also

Examples

#| standalone: true
#| components: [editor, viewer]
#| layout: vertical
#| viewerHeight: 400

## file: app.py
from pathlib import Path

from shiny import App, ui

js_file = Path(__file__).parent / "js" / "app.js"

app_ui = ui.page_fluid(
    "If you see this page before 'OK'-ing the alert box, something went wrong",
    ui.include_js(js_file),
)


app = App(app_ui, None)


## file: js/app.js
alert("If you're seeing this, the javascript file was included successfully.");