无法通过JavaScript文件渲染Lightweight-charts图表
解决Lightweight Charts独立JS文件无法渲染图表的问题
问题根源
- script标签类型错误:引入charts.js时写的
type="javascript"无效,正确类型是text/javascript(现代浏览器可省略该属性,但写的话必须规范) - DOM加载顺序问题:script放在head中,JS代码执行时页面的
container元素还没渲染出来,document.getElementById('container')会返回null,导致图表创建失败
修正方案
方案1:修正script属性并监听DOM加载
修正后的HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Charts</title> <script src="https://unpkg.com/lightweight-charts@3.4.0/dist/lightweight-charts.standalone.production.js"></script> <script src="charts.js" type="text/javascript"></script> </head> <body> <div>Test</div> <div id="container"></div> </body> </html>
修正后的charts.js代码
// 等页面DOM全部加载完成后再初始化图表 document.addEventListener('DOMContentLoaded', function() { const chart = LightweightCharts.createChart(document.getElementById('container'), { width: 900, height: 900 }); const lineSeries = chart.addLineSeries(); lineSeries.setData([ { time: '2019-04-11', value: 80.01 }, { time: '2019-04-12', value: 96.63 }, { time: '2019-04-13', value: 76.64 }, { time: '2019-04-14', value: 81.89 }, { time: '2019-04-15', value: 74.43 }, { time: '2019-04-16', value: 80.01 }, { time: '2019-04-17', value: 96.63 }, { time: '2019-04-18', value: 76.64 }, { time: '2019-04-19', value: 81.89 }, { time: '2019-04-20', value: 74.43 }, ]); });
方案2:将script标签移到body末尾
如果不想修改JS代码,把引入charts.js的script标签放到body最后,确保执行JS时container元素已存在:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Charts</title> <script src="https://unpkg.com/lightweight-charts@3.4.0/dist/lightweight-charts.standalone.production.js"></script> </head> <body> <div>Test</div> <div id="container"></div> <!-- 移到body末尾 --> <script src="charts.js"></script> </body> </html>
此时charts.js可以保留原代码,但建议给chart加上const声明,避免全局变量污染:
const chart = LightweightCharts.createChart(document.getElementById('container'), { width: 900, height: 900 }); const lineSeries = chart.addLineSeries(); lineSeries.setData([ { time: '2019-04-11', value: 80.01 }, { time: '2019-04-12', value: 96.63 }, { time: '2019-04-13', value: 76.64 }, { time: '2019-04-14', value: 81.89 }, { time: '2019-04-15', value: 74.43 }, { time: '2019-04-16', value: 80.01 }, { time: '2019-04-17', value: 96.63 }, { time: '2019-04-18', value: 76.64 }, { time: '2019-04-19', value: 81.89 }, { time: '2019-04-20', value: 74.43 }, ]);
内容的提问来源于stack exchange,提问作者RalphF
相关产品推荐
相关产品推荐

