# Javascript assets in a theme component

**URL:** <https://meta.discourse.org/t/javascript-assets-in-a-theme-component/189109>\
**Category:** Development\
**Created:** [May 4, 2021, 8:19am UTC](https://meta.discourse.org/t/javascript-assets-in-a-theme-component/189109 "2021-05-04T08:19:44Z")\
**Posts on this page:** 1\
**Showing post:** 14

<div class="post-metadata">

**Author:** ![merefield](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/merefield/32/176214_2.png) [@merefield](https://meta.discourse.org/u/merefield)\
**Post date:** [May 6, 2021, 7:19am UTC](https://meta.discourse.org/t/javascript-assets-in-a-theme-component/189109/14 "2021-05-06T07:19:28Z")

</div>

If you just need Just In Time loading of a javascript asset, like I do here where I require a D3 library, you can use this pattern with `Loadscript`:

> <https://github.com/merefield/discourse-tc-tag-cloud/blob/91943c7fdc032f640a7a97aa007fd2a3f34ae5fd/javascripts/discourse/components/tagcloudvis.js.es6#L41>

and further up:

> <https://github.com/merefield/discourse-tc-tag-cloud/blob/91943c7fdc032f640a7a97aa007fd2a3f34ae5fd/javascripts/discourse/components/tagcloudvis.js.es6#L8>

Loadscript returns a `Promise`, so you have to perform a `.then` on the result. (I’m not certain, but assume the result is implicitly cached, so will run faster second time etc.)

As you can see, you can string them together to load several scripts one after the other.

Note that it’s running inside an Ember Component and is fired off the `didInsertElement` hook. Learn more about Ember Components here: [Templates are HTML - Components - Ember Guides](https://guides.emberjs.com/v3.15.0/components/)

Note also the script themselves are housed in `javacsripts/assets` directory.

I based this on @j.jaffeux’s code somewhere used to load in a completely different script (thanks Joffrey! 👍 )

Here’s a Discourse example:

> <https://github.com/discourse/discourse-math/blob/6801b3a481f5749a56944eaa4bf76366eae5a5d7/assets/javascripts/initializers/discourse-math-katex.js.es6#L40>

Tip: always dig through the Official and Pavilion TCs and Plugins that are doing something similar to see how they achieve things :).

---

_[View the full topic](https://meta.discourse.org/t/javascript-assets-in-a-theme-component/189109)._
