JS loading troubles in widgets
-
Hello,
This should be possible. Can you post the code from one of your html widgets so we have a better idea of what's happening?
-
This is a minimal example:
<script src="static/comparisons/Chart.min.js"></script>
<script>
// Set chart dataset defaults.
Chart.defaults.global.elements.line.fill = false;
</script>Yields: "ReferenceError: Chart is not defined"
(This is including the chartjs javascript, only self-served since I had issues with linking outside stuff before.)
-
@tigger You'll need to use
require
, when Chart.js sees that require is available, it will define a module rather then creating the globalChart
.<script> require(['/static/comparisons/Chart.min.js'], function (Chart) { // Set chart dataset defaults. Chart.defaults.global.elements.line.fill = false; }); </script>
You need to use the
require
method in all widgets that useChart
.Chart
will always refer to the same object, just like if it was a global.You can also use urls, it will work the same.
require(['https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'], function (Chart) { ... });
-
Yes, exactly. It keeps everything in it's own scope, and out of the global scope.
It depends what you are trying to do. Can you give an example?
-
@tigger FYI... Chart.js is already available as a r.js module in NodeBB. So, you don't have to load it again from somewhere else.
Just use...
<script> require(['Chart'], function (Chart) { // Set chart dataset defaults. Chart.defaults.global.elements.line.fill = false; }); </script>
-
@pichalite said in JS loading troubles in widgets:
@tigger FYI... Chart.js is already available as a r.js module in NodeBB. So, you don't have to load it again from somewhere else.
Just use...
<script> require(['Chart'], function (Chart) { // Set chart dataset defaults. Chart.defaults.global.elements.line.fill = false; }); </script>
Cool, thanks!
-
I'm having somewhat strange trouble with it - I created 2 fake categories which are static content, I added them from a widget on the category page. One of them links to the webpage with this chart script. Strangely though, if I click back on the category link after having been on the static page with the script (the other one works fine), all my normal category links get rewritten as: /%7Bconfig.relative_path%7D/category/3/open-forum instead of just /category/3/open-forum. Would you have a clue what I broke and how?