htmlwidgets in effect are reusable HTML/JS/CSS components (think simple Polymer or WebComponents) I don’t recommend it, but if we wanted to use an htmlwidget with no R, it is fairly straightforward. Even if you decided not to do this, I think it will be helpful to clear up some of the magic internals of htmlwidgets.

We’ll use the simple but powerful jsonedit from the listviewer package. Its JavaScript binding is very sparse, so I hope it will be a good subject.

Output from a htmlwidget

Let’s start by seeing what happens when we create our htmlwidget. The R code would look something like this.

# give it an empty list() or {} in JavaScript

If we open our developer tools in Chrome, we should see something like this.

screenshot of html from htmlwidget

screenshot of html from htmlwidget

Each htmlwidget will be different, but the ingredients will usually contain:

  1. JavaScript and CSS dependencies
    • htmlwidgets.js
    • js/css for the source libraries which are provided in the htmlwidget yaml screenshot of yaml dependencies
    • the htmlwidget binding - jsonedit.js
  2. HTML tags
    • usually a <div> with an id and class='..widgetname.. html-widget', but depending on the widget might be a different tag or set of tags
    • <script type='application/json' data-for='..widgetid..'>

copy/paste method

easier? way

The data script with data-for piece can be tricky to populate. Many times, it might be easier to manually render our htmlwidget from JavaScript.