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:
this.words.sort(compare);
this.words.map((word) => {
word.size = Math.log(word.count + 1.75) * 30;
word.href = `/tag/${word.text}`;
return word;
});
var _this = this;
this.ensureD3().then(() => {
var layout = d3.layout
.cloud()
.size([settings.tag_cloud_width, settings.tag_cloud_height])
.words(_this.words)
.padding(5)
.rotate(function () {
return 0;
})
.font("Impact")
.fontSize(function (d) {
and further up:
import loadScript from "discourse/lib/load-script";
import DiscourseURL from "discourse/lib/url";
export default Ember.Component.extend({
classNames: "tag-cloud-vis",
words: Ember.computed.alias("model.content"),
ensureD3() {
return loadScript(settings.theme_uploads.d3Lib).then(() => {
return loadScript(settings.theme_uploads.d3Cloud);
});
},
didInsertElement() {
if (!this.site.mobileView) {
this.setup();
}
},
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
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:
}
function katex($elem) {
if (!$elem || !$elem.find) {
return;
}
const mathElems = $elem.find(".math");
if (mathElems.length > 0) {
ensureKaTeX().then(() => {
mathElems.each((idx, elem) => decorate(elem));
});
}
}
function initializeMath(api) {
api.decorateCooked(
function (elem) {
katex(elem);
},
Tip: always dig through the Official and Pavilion TCs and Plugins that are doing something similar to see how they achieve things :).