Include Javascript on Certain Pages in Phoenix Framework Application

Here is one way to achieve this.

The JavaScript you have in the script tag, you move that into a separate file.

You divide your "regular" javascript (to be included in every page) and this custom javascript (to be included in some specific pages) into separate directories. e.g. app/common/standard.js and app/custom/unique.js

You modify your brunch-config.js to as follows:

module.exports = {
 files: {
    javascripts: {
      joinTo: {
        'custom.js': /^app[\\\/]common[\\\/][\S*?]\.js/,
        'app.js': /^app[\\\/]common[\\\/][\S*?]\.js/
        }
    }
}

Then you include app.js in all pages,

<script src="<%= static_path(@conn, "/js/app.js") %>"></script>

but custom.js only in page (or layout) templates that need it.

<script src="<%= static_path(@conn, "/js/custom.js") %>"></script>

1.

Put all that javascript from form.html.eex into its own file (maybe something like js/posts.js).

Add this at the bottom:

export var Post = { run: function() {
  // put initializer stuff here
  // for example:
  // $(document).on('click', '.remove-post', my_remove_post_function)
}}

2.

In your app.html, under <script src="#{static_path(@conn, "/js/app.js")}"></script> add this:

<%= render_existing @view_module, "scripts.html", assigns %>

3.

Then, in your view (probably views/post_view.ex), add a method like this:

def render("scripts.html", _assigns) do
  ~s{<script>require("web/static/js/posts").Post.run()</script>}
  |> raw
end

Conclusion

Now the javascript file post.js will only be loaded when the post view is being used.