Skip to content

Commit 05a3755

Browse files
Merge pull request #37 from umairabid/main
Add load theme function to load themes with window context
2 parents 1e4b122 + 950a8f6 commit 05a3755

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,27 @@ import "echarts/theme/dark"
129129
130130
4) customize charts if needed. See available options or [official documentation](https://echarts.apache.org/examples/en/index.html).
131131
132+
### Loading Themes
133+
134+
Themes can be loaded as shown in examples above. However, in some cases where
135+
themes are included in environment where `this` does not point to `window`, you
136+
might get errors. In that case, you can use loadTheme helper to load themes by
137+
name. For example, instead of
138+
139+
```javascript
140+
import 'echarts/theme/dark'
141+
```
142+
you can do
143+
144+
```javascript
145+
// application.js
146+
import "echarts"
147+
import "echarts.themeloader"
148+
149+
// Load the desired theme dynamically
150+
RailsCharts.loadTheme('dark');
151+
```
152+
132153
## Options
133154
134155
```ruby
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
(function() {
2+
window.RailsCharts = window.RailsCharts || {};
3+
window.RailsCharts.loadedThemes = window.RailsCharts.loadedThemes || [];
4+
5+
window.RailsCharts.loadTheme = function(themeName) {
6+
document.addEventListener('DOMContentLoaded', () => {
7+
if (typeof echarts === 'undefined') {
8+
console.error('ECharts is not loaded. Please ensure echarts.js is included.');
9+
return;
10+
}
11+
12+
if (window.RailsCharts.loadedThemes.includes(themeName)) {
13+
console.warn(`Theme '${themeName}' is already loaded.`);
14+
return;
15+
}
16+
17+
const script = document.createElement('script');
18+
script.type = 'text/javascript';
19+
script.src = `/assets/echarts/theme/${themeName}.js`;
20+
script.onload = () => {
21+
console.log(`Theme '${themeName}' loaded successfully.`);
22+
};
23+
script.onerror = () => {
24+
console.error(`Failed to load theme: /assets/echarts/theme/${themeName}.js`);
25+
};
26+
document.head.appendChild(script);
27+
});
28+
};
29+
})();

0 commit comments

Comments
 (0)