ryloric
Javascript in Phoenix templates
Hi!,
What’s the best way to sprinkle bits of javascript for use inside EEx templates, just simple things like handling button clicks, hiding tags etc. I’ve been using a <script> tag at the bottom of the template with some common functions in a global object created in assets/js/app.js.
Is this a reasonable pattern? What are recommended/best-practices around this?
Sorry if this question is a bit naive, I’m pretty new to web-dev and js in general.
Most Liked
peerreynders
Welcome to the forum!
A vanilla phoenix project is structured around modular javascript.
If you don’t want to use a bundler you can always specify:
mix phx.new PATH --no-webpack
Any additional assets are then kept directly under priv/static.
It may be necessary to adjust the endpoint to pick up assets under non-standard directories.
That being said npm is currently the de facto mechanism for publishing JavaScript libraries (essentially making bower redundant) - so there is significant drive towards adopting a bundler that works with npm.
adrianrl
Hi, you can create helper functions into separate files, it’s a very common and modular approach, something like:
helpers/buttons.js - Handle clicks for buttons
helpers/inputs.js - Handle events for inputs
helpers/animations.js - Handle animations for elements
Then you just import those files inside your main script to include them in your bundle.
Also I’d recommend using the defer attribute rather than putting <script> at the bottom. With defer the browser will download the script while the HTML is being parsed. If you put <script> at the bottom, the browser will parse the HTML and when it hits the <script> tag, it will download the script, so technically is slower.
Here’s a nice article about this: https://flaviocopes.com/javascript-async-defer/
I’d definitively not recommend async if you split your bundle.
sfusato
Take a look at Stimulus. This is exactly its use case.
Stimulus is a JavaScript framework with modest ambitions. It doesn’t seek to take over your entire front-end—in fact, it’s not concerned with rendering HTML at all. Instead, it’s designed to augment your HTML with just enough behavior to make it shine. Stimulus pairs beautifully with Turbolinks to provide a complete solution for fast, compelling applications with a minimal amount of effort.









