Skip to content

Instantly share code, notes, and snippets.

@thmsmlr
Created February 14, 2024 16:54
Show Gist options
  • Save thmsmlr/7ec80f447ad333ebc12b4c7f90845c81 to your computer and use it in GitHub Desktop.
Save thmsmlr/7ec80f447ad333ebc12b4c7f90845c81 to your computer and use it in GitHub Desktop.
Code Splitting for Phoenix LiveView Hooks
// assets/js/app.js
window._lazy_hooks = window._lazy_hooks || {};
let lazyHook = function(hook) {
return {
mounted() { window._lazy_hooks[hook].mounted(...arguments) },
beforeUpdate() { window._lazy_hooks[hook].beforeUpdate(...arguments) },
updated() { window._lazy_hooks[hook].updated(...arguments) },
destroyed() { window._lazy_hooks[hook].destroyed(...arguments) },
disconnected() { window._lazy_hooks[hook].disconnected(...arguments) },
reconnected() { window._lazy_hooks[hook].reconnected(...arguments) }
}
}
let Hooks = {};
Hooks.MyHeavyHook = lazyHook("MyHeavyHook")
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, { params: { _csrf_token: csrfToken }, hooks: Hooks })
<!-- lib/demo_web/live/heavy_live.html.heex -->
<div>
<script type="text/javascript" src={~p"/heavy_page.js"}>
</script>
<h3>This page is really heavy and a liveview</h3>
<div id="foobar" phx-hook="MyHeavyHook">
Using the hook
</div>
</div>
// priv/static/heavy_page.js
window._lazy_hooks = window._lazy_hooks || {};
window._lazy_hooks["MyHeavyHook"] = {
mounted() { alert("heavy mount") },
updated() { console.log("heavy update") }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment