Best way to generate JavaScript on the fly

I’m writing an embed functionality that uses a JavaScript file to create an iframe. The JavaScript file is per database record and needs to be (I think) generated on the fly.

I thought about adding a js format to the accepts plug and a foo.js.eex template, and interpolating Elixir variables in the template. But this approach has several draw backs:

  1. I can’t embed the route in a script tag without using ?_format=js, which seems strange. For example: <script src="http://foo.bar/embed/1?_format=js"></script>
  2. Phoenix raises an error and asks me to disable request forgery for js requests. This means I need a separate pipeline for JS routes.

Another way is to add the identifying data to data attributes and use the same file. For example:

<script src="path_to_file.js" data-slug="foo" data-type="bar" etc...></script>

Then from within the file I would get those data attrs. I haven’t tested this, so I’m not sure how well it would work.

What’s a better way to do this?

1 Like

I saw a nice method that stripe uses.

Basically they include the data on the page as JSON and give the tag an ID.

<script src="common.js"></script>
<script type="application/json" id="foo_data">{foo: "bar"}</script>

Then common.js can find foo_data by the tag’s ID.

4 Likes