Introducing ECharts via CDN
What is CDN
CDN (Content Delivery Network) is a system that caches resources on edge servers distributed globally, allowing users to retrieve resources from the nearest server, thereby significantly improving loading speeds. For front-end developers, CDN is one of the common methods for importing third-party libraries, especially large visualization libraries like ECharts.
Why Use CDN to Import ECharts
ECharts, as an open-source data visualization library from Baidu, has a compressed full version of around 700KB. If installed via npm and bundled, it would increase the size of the project's build output. Using CDN to import ECharts offers the following advantages:
- Reduces the project's build size
- Leverages CDN caching—users may already have ECharts cached when visiting different websites
- No need for local installation and building
- Flexible version switching
ECharts Resources Provided by Major CDN Providers
Popular CDN providers offer mirrors of ECharts:
-
jsDelivr (recommended):
<!-- Latest version --> <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script> <!-- Specific version --> <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
-
cdnjs:
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
-
BootCDN:
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
-
UNPKG:
<script src="https://unpkg.com/echarts@5.4.3/dist/echarts.min.js"></script>
Basic Usage Example
After importing ECharts via CDN, you can create a simple bar chart as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts CDN Example</title>
<!-- Import ECharts -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
</head>
<body>
<!-- Prepare a DOM with specified dimensions for ECharts -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// Initialize the ECharts instance
var myChart = echarts.init(document.getElementById('main'));
// Specify the chart's configuration and data
var option = {
title: {
text: 'ECharts CDN Import Example'
},
tooltip: {},
legend: {
data: ['Sales']
},
xAxis: {
data: ["Shirt","Wool Sweater","Chiffon Shirt","Pants","High Heels","Socks"]
},
yAxis: {},
series: [{
name: 'Sales',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// Display the chart using the specified configuration and data
myChart.setOption(option);
</script>
</body>
</html>
On-Demand Import to Reduce Size
If only core ECharts functionality is needed, you can import it on-demand via CDN:
<!-- Import the core module -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.core.min.js"></script>
<!-- Import other modules as needed -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/map/js/china.js"></script> <!-- China map -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/extension/dataTool.min.js"></script> <!-- Data tools -->
Using Themes
ECharts supports themes, which can also be imported via CDN:
<!-- Import the dark theme -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/theme/dark.js"></script>
<script>
// Use the theme
var chart = echarts.init(document.getElementById('main'), 'dark');
</script>
Managing Multiple Chart Instances
When there are multiple charts on a page, it's recommended to manage instances uniformly:
// Collection of chart instances
var charts = {};
// Initialize a chart
function initChart(domId, option) {
var chart = echarts.init(document.getElementById(domId));
chart.setOption(option);
charts[domId] = chart;
return chart;
}
// Adjust all charts uniformly when the window is resized
window.addEventListener('resize', function() {
Object.values(charts).forEach(function(chart) {
chart.resize();
});
});
Error Handling and Fallback Solutions
To handle CDN loading failures, prepare a fallback solution:
<script>
// Check if ECharts loaded successfully
function checkECharts() {
if (typeof echarts === 'undefined') {
// CDN failed, use a backup CDN
var script = document.createElement('script');
script.src = 'https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js';
document.head.appendChild(script);
// If the backup CDN also fails, display an error message
setTimeout(function() {
if (typeof echarts === 'undefined') {
document.getElementById('chart-container').innerHTML =
'<p>Failed to load the chart. Please check your network connection.</p>';
}
}, 3000);
}
}
// Check after the page loads
window.addEventListener('load', checkECharts);
</script>
Performance Optimization Recommendations
-
Preload: Start loading ECharts resources early in the page load process
<link rel="preload" href="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js" as="script">
-
Asynchronous Loading: Use the
async
ordefer
attributes<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js" defer></script>
-
Version Pinning: Always use a specific version instead of "latest" to avoid unexpected issues from updates
-
Resource Monitoring: Add resource loading monitoring
var script = document.createElement('script'); script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js'; script.onload = function() { console.log('ECharts loaded successfully'); }; script.onerror = function() { console.error('Failed to load ECharts'); }; document.head.appendChild(script);
Integration with Other Libraries
ECharts can be used alongside other libraries imported via CDN, such as:
<!-- Import jQuery -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<!-- Import ECharts -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script>
$(document).ready(function() {
// Use jQuery to get DOM elements
var chartDom = $('#main')[0];
var myChart = echarts.init(chartDom);
// Fetch data via AJAX
$.get('/api/chart-data').then(function(data) {
myChart.setOption(data);
});
});
</script>
Dynamically Loading Extensions
Some advanced ECharts features require additional extensions:
// Dynamically load the Baidu Map extension
function loadBMapExtension() {
return new Promise(function(resolve, reject) {
var script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/extension/bmap.min.js';
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// Use the extension
loadBMapExtension().then(function() {
var chart = echarts.init(document.getElementById('map-chart'));
chart.setOption({
bmap: {
center: [116.46, 39.92],
zoom: 11,
roam: true
},
series: [{
type: 'scatter',
coordinateSystem: 'bmap',
data: [[120, 30, 1], [116.46, 39.92, 2]]
}]
});
});
Version Management and Upgrade Strategy
- Pin Minor Versions: Use version ranges like
~5.4.0
to allow patch updates - Test New Versions: Verify new versions in a test environment before updating production
- Version Rollback: Keep old version references for quick rollback if issues arise
<!-- Use a minor version range -->
<script src="https://cdn.jsdelivr.net/npm/echarts@~5.4.0/dist/echarts.min.js"></script>
<!-- Keep an old version as backup -->
<!-- <script src="https://cdn.jsdelivr.net/npm/echarts@5.3.3/dist/echarts.min.js"></script> -->
Security Considerations
- HTTPS: Always use HTTPS to import CDN resources
- SRI: Use Subresource Integrity checks
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js" integrity="sha384-7wA7z7P6E5yS4z7O5yX5S4c5y5h5R5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5" crossorigin="anonymous"></script>
- CSP: If using Content Security Policy, configure the appropriate CDN domains
Best Practices in Real Projects
-
Encapsulate Chart Components: Wrap chart initialization logic into reusable components
function createChart(container, options) { var chart = echarts.init(document.getElementById(container)); chart.setOption(options); return { update: function(newOptions) { chart.setOption(newOptions); }, dispose: function() { chart.dispose(); } }; }
-
Memory Management: In single-page applications, dispose of unused chart instances promptly
// During route changes window.addEventListener('beforeunload', function() { Object.values(charts).forEach(function(chart) { chart.dispose(); }); });
-
Responsive Design: Combine CSS media queries and the
resize
method for responsive charts.chart-container { width: 100%; height: 400px; } @media (max-width: 768px) { .chart-container { height: 300px; } }
Debugging and Troubleshooting
-
Version Conflicts: Ensure all instances use the same ECharts version
-
Loading Order: Ensure dependencies load after the core library
-
Console Checks:
// Check ECharts version console.log('ECharts version:', echarts.version); // Check registered components console.log('Registered components:', echarts.getComponents());
-
Common Error Handling:
try { var chart = echarts.init(document.getElementById('main')); chart.setOption(options); } catch (e) { console.error('ECharts error:', e); // Display a user-friendly error message document.getElementById('main').innerHTML = '<div class="error">Chart initialization failed. Please refresh and try again.</div>'; }
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
下一篇:npm安装与模块化使用