How to organize javascript code in phoenix?

Question about how to organize javascript code in phoenix. Is it normal to write something like this that will be included in app.js. The id #foo will only appear on one page and so the event listener will only be relevant on that page even though the javascript code will be part of app.js and so be loaded in every single page. Is this normal best practice?

if (document.querySelector('#foo')) {
  document.querySelector("#foo").addEventListener(function() {
    ...
  });
}

Personally, I would not put something for a specific page in that file. You could use a script tag on that page or a hook.

1 Like