Утечка памяти в браузере при использовании jQuery, AJAX, API визуализации Google и setTimeout () - PullRequest
2 голосов
/ 23 ноября 2011

Я замечаю утечку памяти в браузере при выполнении приведенного ниже кода, так что компьютер перестает отвечать на запросы, если я оставляю страницу панели мониторинга загруженной более 24 часов.

Код должен быть понятен: данные «часовых показателей» извлекаются вызовом AJAX скрипта Perl и передаются в виджет LineChart API визуализации Google, и я хотел бы добиться автоматического обновления веб-страница с заданным интервалом (на данный момент установлено 5 минут). Обновление работает, но где-то есть проблема, поскольку потребление памяти постоянно увеличивается.

Нужно ли закрытие Javascript? Извините, если ошибка очевидна, я очень новичок в разработке AJAX / JQuery ...

<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">

// Load the Visualization API
google.load('visualization', '1', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);

function drawChart() {

  var jsonDatahourlyindicators = $.ajax({
      type: "GET",
      url: "http://localhost/cgi-bin/hourlyindicators.pl",
      dataType: "json",
      cache: false,
      async: false
      }).responseText;

  // Create our data table out of JSON data loaded from server.
  var datahourlyindicators = new google.visualization.DataTable(jsonDatahourlyindicators);

  // Create data view
  var viewfpy = new google.visualization.DataView(datahourlyindicators);

  // Select columns to display
  viewfpy.setColumns([0,1,2]);

  // Instantiate and draw our chart, passing in some options.
  var charthourlyfpy = new google.visualization.LineChart(document.getElementById('hourlyindicators_div'));
  charthourlyfpy.draw(viewfpy,
                      {width: 800, 
                       height: 400, 
                       title: 'Today\'s Hourly Indicators',
                       vAxis: {title:"Indicator Value",viewWindowMode:'explicit',viewWindow:{min:minfpy,max:100},textStyle:{color:'black',fontSize:20}},
                       hAxis: {title:"Hour of Day"},
                       series: {0:{color:'blue',lineWidth:5,pointSize:10},
                                1:{color:'green',lineWidth:10,visibleInLegend:false}}
                       });

  // Auto-refreshes every 5 minutes
  setTimeout('drawChart()', 5*60*1000); 
}
</script>
</head>

<body>
<div id="hourlyindicators_div"></div>
</body>
</html>

1 Ответ

0 голосов
/ 23 ноября 2011

изменить на этот код - я проверяю его с помощью Chrome Profiler, и он выглядит лучше

  <html>
    <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);
      var viewfpy = null;
       var charthourlyfpy = null;
    function drawChart() {
     var jsonDatahourlyindicators = $.ajax({
      type: "GET",
      url: "http://localhost/cgi-bin/hourlyindicators.pl",
      dataType: "json",
      cache: false,
      async: false
      }).responseText;



      // Create data view
      viewfpy = new google.visualization.DataView(datahourlyindicators);

      // Select columns to display
      viewfpy.setColumns([0,1]);

      // Instantiate and draw our chart, passing in some options.
      if (charthourlyfpy == null)
      {
        charthourlyfpy = new google.visualization.LineChart(document.getElementById('hourlyindicators_div'));
     }
      charthourlyfpy.draw(viewfpy,
                          {width: 800, 
                           height: 400, 
                           title: 'Today\'s Hourly Indicators',
                         //  vAxis: {title:"Indicator Value",viewWindowMode:'explicit',viewWindow:{min:minfpy,max:100},textStyle:{color:'black',fontSize:20}},
                           hAxis: {title:"Hour of Day"},
                           series: {0:{color:'blue',lineWidth:5,pointSize:10},
                                    1:{color:'green',lineWidth:10,visibleInLegend:false}}
                           });

      // Auto-refreshes every 5 minutes
      setTimeout('drawChart()',1000); 
    }
    </script>
    </head>

    <body>
    <div id="hourlyindicators_div"></div>
    </body>
    </html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...