What is the canonical way of adding JavaScript to a `xaringan` presentation?

I'm trying to add JavaScript to a xaringan document, and none of the standard mechanisms seem to work.

For example, using a {js} chunk doesn't work.

alert("made it here");

Neither does a <script> tag:

alert("made it here");

In both cases xaringan seems to simply insert the JavaScript as text, and I never get the alert.

A kludgy workaround

In the end I found a mechanism that works, based on the rmarkdown::includes() function. This works by creating an html file that contains the script, and then inserting it via the xaringan yaml header.

This is my toc.html:

alert("made it here");

And then I insert it in my yaml header like this:

        - 'toc.html'

There has to be a better way. Can you help me find it?

Not sure if it is better, but you can save your script in a file - consider macros.js - and have it executed from nature:beforeInit: section of your front matter

    css: ["default", "./libs/JLA-fonts.css"]
    lib_dir: libs
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
      ratio: "16:9"
      beforeInit: "./libs/macros.js"

That's what I'd do, too.

However, I suggest you use a different folder. The libs/ folder was specified by the lib_dir, and it will be automatically generated to include other JS/CSS files, which means this folder could be automatically removed, so you'd better not put anything manually created in this folder.

BTW, @andrie's motivating use case was https://github.com/yihui/xaringan/issues/217. The beforeInit option may not work in that case because the JS code is executed before remark.js initializes the slides from Markdown to HTML. In other words, beforeInit is too early, unless you delay the execution in a certain JS event (such as onload). You'd better use includes: after_body instead of beforeInit or includes: in_header.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.