2015-04-01 40 views
2

我使用的是MVC剃刀foreach渲染图表加载时间长,有时超过150如何使用队列,以防止

我这是怎么生成的脚本来渲染多个HighCharts:

@{chartCount = 0;} 
@foreach (var item in Model.ChartRows.Where(m => !m.SummaryRow)) 
    { 
     $('#[email protected](chartCount)').highcharts({ 
      //code removed for brevity 
     }); 
     chartCount++; 
    } 

然后在我的HTML我用这个来呈现容器:

@for (int i = 0; i < chartCount; i++) 
    { 
     <div id="[email protected](i)"></div><br /> 
    } 

然而,当有项目100个在ChartRows,页面可以采取LON g突然之前加载所有图表。 我在HighCharts网站上看了一下,发现了一种名为“Sparkline”的图表类型,jsFiddle example显示了一种方法,即可以使用setTimout来延迟渲染,然后将它们渲染为“块”。

对于我来说,我需要这样做,我将不得不从脚本中删除所有数据(或者至少从item.填充任何内容),而是将7个以上的数据属性添加到每个HTML容器并使用jQuery来获取这些数据属性来填充图表数据。我对这种方法并不感到兴奋,因为它可能会让故障排除变成一场噩梦。

是否有人知道是否有可能将每个正在渲染的图表添加到某种类型的队列中,以便它们一次呈现1而不是浏览器在同一时间全部渲染它们?

+0

也许更好的是在可见部分负荷图页面,然后抓住滚动事件并加载其他? – 2015-04-01 14:06:21

+0

谢谢@SebastianBochan,我正在考虑某种“懒惰”。我真的希望可以有一些方法可以做到这一点,而无需添加额外的标记(这通常是拉载要求)。 – wf4 2015-04-01 14:24:47

+0

但您刚给我一个主意!我将尝试创建每个图表作为var /函数,然后调用每个图表以使用计时器进行渲染... – wf4 2015-04-01 14:25:27

回答

1

这是我做的:

<script> 
var chartFunctions = []; 
@foreach (var item in Model.ChartRows.Where(m => !m.SummaryRow)) 
{ 
    var [email protected](item.ID) = function() { 
     $('#[email protected](item.ID)').highcharts({ 
      //code removed for brevity 
     }); 
    } 
    //add this function into the array 
    chartFunctions.push([email protected](item.ID)); 
} 


    function renderCharts() { 
     var time = +new Date(), 
      len = chartFunctions.length; 

     for (i = 0; i < len; i += 1) { 

      //call each function in the function array 
      chartFunctions[i](); 

      // If the process takes too much time 
      if (new Date() - time > 500) { 
       chartFunctions.splice(0, i + 1); 
       setTimeout(renderCharts, 0); 
       break; 
      } 
     } 
    } 

    renderCharts(); 
</script> 

而且我还需要使用一个foreach到chartID和数据筒匹配:

@foreach (var item in Model.ChartRows.Where(m => !m.SummaryRow)) 
{ 
    <div id="[email protected](item.ID)"></div><br /> 
}