简体   繁体   English

一页上有多个Google图表-要有效地加载库?

[英]Multiple Google Charts on one page - Loading Library efficiently?

I've seen MANY people ask about having multiple Google Charts on one page, and the answer is always "your html/js is wrong", or "just add all of them in one function that's called in the setOnLoadCallback". 我已经看到很多人问在一个页面上有多个Google Charts,答案总是“您的html / js错误”,或者“只是将所有这些都添加到setOnLoadCallback中调用的一个函数中”。

My issue is a bit different. 我的问题有点不同。 What if I want buttons, client side, that, when clicked, generate a Google Chart. 如果我要在客户端单击按钮,该按钮单击后会生成Google图表怎么办。 Do I need to call "google.load(....)" every time, and then setOnLoadCallback as well, or is there some way to load it ONCE, and then from that point forward just use the already loaded objects? 我是否需要每次都调用“ google.load(....)”,然后也调用setOnLoadCallback,或者是否有某种方法可以一次加载它,然后从那时开始只使用已经加载的对象?

The only thing I can think of is to store some flag that's updated on the very first google.setOnLoadCallback, and if flag is set, don't load it again, but if someone clicks a few buttons quickly they will all already have issued "load" function calls. 我唯一能想到的就是在第一个google.setOnLoadCallback上存储一些已更新的标志,如果设置了标志,则不要再次加载它,但是如果有人快速单击几个按钮,他们将已经发出了“加载”函数调用。

Basically I want one generic function that I can call (I will create it myself) but I don't want the function calling google.load everytime, it just feels really inefficient. 基本上,我想要一个可以调用的通用函数(我自己创建),但我不想每次都调用google.load,这真的感觉效率很低。

How do I go about this efficiently? 我如何有效地做到这一点?

google.load should indeed be called only once per page load. 实际上,每个页面加载一次仅应调用一次google.load You don't have to put all your charts into one function, you can create several functions and call them whenever you want, as following: 您不必将所有图表都放在一个函数中,可以创建多个函数并在需要时调用它们,如下所示:

google.load('visualization', '1.1', {
    packages: ['corechart', 'controls'],
    language: 'en'
});

function drawFirstVisualizations() {
    chart1 = new google.visualization.ChartWrapper({
        'chartType': 'LineChart',
    });

    chart2 = new google.visualization.ChartWrapper({
        'chartType': 'LineChart',
    });

    chart1.draw();
    chart2.draw();
}

function drawSecondVisualizations() {
    chart3 = new google.visualization.ChartWrapper({
        'chartType': 'LineChart',
    });

    chart4 = new google.visualization.ChartWrapper({
        'chartType': 'LineChart',
    });

    chart3.draw();
    chart4.draw();
}

google.setOnLoadCallback(drawFirstVisualizations);

function functionBeingCalledLater() {
    google.setOnLoadCallback(drawSecondVisualizations);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM