How to include JavaScript into widgets?
-
Hello everyone,
I am developing my own widgets for NodeBB and some of them require JavaScript. I would like to include the JS for the widget only when the widget is actually present on the page and was wondering if there is a way to do this. My alternative would be to include the JS on each page using the
"scripts"
parameter in theplugin.json
file.I know that when developing regular plugins, you can tell NodeBB to include the JS only when the page that requires it loads, by defining the JS file in the
"modules"
parameter in theplugin.json
file. However, I cannot get this mechanism to work when rendering my widgets usingwidget.html = await widget.req.app.renderAsync("widgetTemplate", {});
.I tried using require in the template like this
<script require("./public/lib/widgetTemplate", function (module) { } module.init(); }); </script
but then I get the JavaScript console error message `ReferenceError: Can't find variable: require'.
Any help would be greatly appreciated! Thanks in advance.
-
Add your module for the widget as usual via the "modules" section in plugin.json, and then you can require it dynamically in your widget html like so.
<div>mywidget</div> <script> (async () => { const myWidget = await app.require("mywidgetmodule"); console.log(myWidget); })(); </script>
-
Thanks @baris for the code snippet. I had to modify it a bit to have it run only after the DOM is fully loaded as otherwise app.require wasn't available:
<script> document.addEventListener("DOMContentLoaded", async () => { if (typeof app !== 'undefined' && typeof app.require === 'function') { const myWidget = await app.require("mywidgetmodule"); myWidget.init(); } else { console.error("app.require is not available."); } }); </script>
If you have suggestions how to do it better feel free to tell me. However, my problem is solved, so thank you!
-