I’d like to create a LiveComponent (actually an Surface component) to handle a Leaflet map.
Is there a way to have live view load JS/CSS into the page only when the component is mounted. Something like dynamically adding the following to the head section.
leaflet.css and leaflet.js are not my code. It’s provided by Leafet so I just addeed these files to priv/static. I’d like to have them loaded (added in the HTML <head> section) when my map component is mounted.
That should create a <link> tag pointing to your css in the document head. You may also want to check if the file was already loaded so you don’t append the link multiple times, maybe with just a module variable and doing something like if(!css_loaded) { ... }.
I’m doing something similar for a personal library that lazy loads component definitions and it works fine.
Back to the browser, I can see this error in the browser console:
Uncaught ReferenceError: L is not defined
mounted ScubananaWeb.Live.Components.Map.hooks.js:14
Displaying the windows object in the console, I can see there’s a L object !
I thinks L is not initialized yet when I create the map (may be JS file is loading). Is there a way to delay it ?
I tried defer: false but it doesn’t seem to work.
//page.html.heex
<noscript>
<script phx-hook="evaljs" id="eval0">
alert("run in liveview")
console.log(this) // the `this` is of mounted function
</script>
</noscript>