Hey,
I’m trying to have some javascript to only load on a certain pages; specifically I’m trying to load code that operates with stripe.js bindings only on a page with Stripe Checkout information, rather than loading the js file everywhere.
I’ve found some old tutorials from the olden days when Phoenix had views, but with the new organisational model from 1.7 I can’t seem to crack it.
NB: this is not liveview specific.
Does anyone have some blueprint I can follow to get this done?
I’m assuming you are using the default esbuild config in a greenfield Phoenix 1.7 project, so in your config.exs you need to add the splitting option as well as tell esbuild to use the ESM format.
Personally I’m interested to know if/how it can be done with LiveView (since the template is rendered outside of it, if I understood the work done for favicons?)
Our solution is a bit naive and since the website is mostly traditional views it works well, for heavy LiveView, can’t say, but I think the BeaconCMS solutions works with LiveView, but not sure.
I do think this would be something nice to have by default on Phoenix, Live Style and Script injection, even though like I showed above, Scripts are pretty easy, styles not so much.
Right, and btw if phoenix_live_head doesn’t yet support dynamic scripts it’d be useful to add your solution to it so it’s all in one place even if not upstream.
Thanks so much @greven, this helped me import MapLibre without causing my app.js file to grow to 5mb! Some additional notes for anyone who stumbles onto this thread:
Update the app.js script tag; change type="text/javascript" to type="module"
Wherever you import your hooks, add: const { MyHook } = require("./my-hook"); Hooks.MyHook = MyHook;