Created
February 14, 2024 16:54
-
-
Save thmsmlr/7ec80f447ad333ebc12b4c7f90845c81 to your computer and use it in GitHub Desktop.
Code Splitting for Phoenix LiveView Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 }) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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