Import Javascript file from Assets

I can’t for the life of me figure out the relative path to import a Javascript file stored in Assets.

The documentation states (regarding the Native Libraries section):

This is a great place to add a <script> tag to pull in an external library (or a .js file in your app’s Assets). You can also use <link> tags to refer to external CSS.

https://anvil.works/docs/client/javascript#calling-python-from-javascript

But gives no examples. Neither ./file-in-assets.js nor file-in-assets.js work.

The trick here is to defer some initialization to after the page loads (i.e., run the scripts after the page has loaded, not before). Native Libraries is injected into the head–no good. I can use <script defer ....> but only if I can put the actual initialization calls in my own Javascript file. Seems logical to create one in Assets (the designer even offers the .js extension when creating a new file), but with no way to ever call it, this capability is useless.

Where are the Assets relative to the loaded page???

John

1 Like

P.S. Can’t put this in the HTML template because this app is being used as a shared library. Stuff in Native Libraries is automatically included in apps that import this one, but the templates would be different. Patching this into the main app would create a maintenance nightmare.

Ok, it’s actually documented here:

https://anvil.works/docs/client/themes-and-styling

Relative path would be _/theme/filename.js

This works in the component, but my guess is it will not work when the component is imported into another app (because the base path of that app will not point to correct location).

Not sure there’s an ideal solution here. I could use the absolute path of the component app, but that’s a little scary, and may create XSS issues when my main app is served off a custom domain.

Another thought would be to create the initialization function in Native Libraries, which will be run in the header, and then call it if from Python when I set up the form.

Any guidance from people doing this would be appreciated.

John

4 Likes

You can get the absolute path of your app by doing anvil.server.get_app_origin() which might be useful

1 Like