I've got a bit of Javascript that I only want to include on certain pages in my Phoenix application.
Right now I've got the Javascript inside a script tag in myapp/web/templates/post/form.html.eex
.
I understand that I can move the JavaScript to web/static/js/app.js
...but I don't want to include the Javascript on every page (it's only required on 2 specific pages).
What's the best way to load this section of Javascript on certain pages in my application without duplication the code and violating the DRY principle?
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) }}
In your app.html, under <script src="#{static_path(@conn, "/js/app.js")}"></script>
add this:
<%= render_existing @view_module, "scripts.html", assigns %>
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
Now the javascript file post.js will only be loaded when the post view is being used.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With