Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include Javascript on Certain Pages in Phoenix Framework Application

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?

like image 445
Andrew Hendrie Avatar asked Apr 14 '16 17:04

Andrew Hendrie


2 Answers

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.

like image 97
cmititiuc Avatar answered Sep 24 '22 04:09

cmititiuc


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> 
like image 33
Asif Shiraz Avatar answered Sep 22 '22 04:09

Asif Shiraz