axelson

axelson

Scenic Core Team

Is it possible to have page-specific javascript with LiveView?

One of my LiveView view’s has a very heavy javascript dependency so I want to avoid loading it for every page on the site, while still using live_redirect or similar between the two (avoiding a full-page load). However, I’m running into
https://github.com/patrick-steele-idem/morphdom/issues/178
This means that any <script> tag that I put into the page will not be executed. Of course there are a plethora of work-arounds: https://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml But I figured that someone else has probably tried to solve this before so I am curious what other people have tried or are using.

Most Liked

rhcarvalho

rhcarvalho

This is one of the two best threads that come up from search on the topic, so reviving it with an up-to-date solution for the benefit of all.

Just like the OP, I wanted to use a heavy JS library in a single page without compromising the bundle size for the rest of the app.

Nowadays Phoenix projects use esbuild by default, and modern browsers support ESM modules and dynamic import.

To my surprise, asking Gemini 3 produced a reasonable output, hinting at the right things. In a nutshell:

  • Update the esbuild config in config/config.exs to output the bundle as an ESM module and enable code-splitting:
      --format=esm
      --splitting
  • Update the root template to load the app.js as a module:
- <script defer phx-track-static type="text/javascript" src={~p"/assets/js/app.js"}>
+ <script phx-track-static type="module" src={~p"/assets/js/app.js"}>
  • Within a JS hook, import the dependency in the mount() callback.
Hooks.MyHook = {
  async mounted() {
    await import("...")
  }
}
  • Alternatively, import the dependency within an event handler.
window.addEventListener("myapp:action-with-heavy-dependency", event => {
  import("...").then(...)
})

With that setup, esbuild should produce a small bundle for app.js, loaded on all pages, and additional files that are only imported/downloaded/executed when needed.

Resources

dbern

dbern

I’m using Webpack 4.43.0. I didn’t notice the docs are for v5, but the dynamic imports are certainly working for me.

I’m going to open-source YouMeet when it launches, so I don’t have the full repo open to browse yet, but here are some snippets that I think covers it.

Here’s an example hook to load a fancy WYSIWYG editor that’s using Vue:

hooks.Editor = {
  mounted() {
    const phoenix = this;
    const target = this.el.getAttribute('phx-target');
    const Editor = () => import(/* webpackChunkName: "editor" */ "./components/Editor.vue");
    () => import(/* webpackChunkName: "highlight" */ "./syntax-highlighter");

    new Vue({
      el: this.el,
      provide: function() {
        return {
          publish: this.publish
        };
      },
      methods: {
        publish: payload => phoenix.pushEventTo(target, "editor-update", payload)
      },
      render: createElement =>
        createElement(Editor, {
          props: {
            initialValue: phoenix.el.dataset.initialValue,
            placeholder: phoenix.el.dataset.placeholder,
          }
        })
    });
  }
};

On the LiveView EEX to load it (actually a LiveComponent but should be about the same)

<div phx-update="ignore" id="Editor-<%= @id %>">
  <div data-placeholder="<%= html_escape(@description_placeholder) %>" 
       data-initial-value="<%= html_escape(input_value(f, :description)) %>" 
       phx-target="<%= @myself %>" 
       phx-hook="Editor" 
       class="container flex h-screen m-4">
  </div>
</div>

and in my Webpack config:

// all the configs plus this:
  output: {
    filename: "[name].js",
    chunkFilename: "[name].bundle.js",  // <-- this line
    path: path.resolve(__dirname, "../priv/static/js"),
    publicPath: "/js/"
  },
// ... no optimizations key
// this may imply that you need to split code yourself.

EDIT: There should be a GIF right here, but it doesn’t seem to load? Sorry, it’s just illustrating how navigating from one LiveView without the script, and then clicking a link to another liveview does trigger the JS fetch and import.
dynamic-import-via-hook

Hopefully I didn’t miss anything!

polypush135

polypush135

What I’ve learned is that if you are using webpack you should be able to dynamically load bundles per hook.
This is how I’m currently doing it.

By using this style in importing.

let Hooks = {
  PageIndex: {
    mounted() {
      import('@mojs/core').then(mojs => {})
...

It only works if you import this way.

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New

Other popular topics Top

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement