A
A
Anton2015-11-29 16:44:11
JavaScript
Anton, 2015-11-29 16:44:11

How to fix a memory leak in Chrome?

In Opera, everything works fine, in Chrome it constantly gives out "Oops" and a message about the lack of memory.
Dear experts jquery and javascript. I'm not asking you to parse the code line by line, but I'm only asking you to skim through the code and point out blunders that may be present in my pile of code (like nesting getJSON into each other, or something ..) Thanks in advance!

draggableMap: function() {
        var $map = $('#image-container'),
            $parent = $('.flats-wrapper'),
            $build = $('.building', $map),
            $schemePopup = $('#scheme-popup');
    var $part1 = $schemePopup.find('.part1'),
      $part2 = $schemePopup.find('.part2'),
      $part3 = $schemePopup.find('.part3');
    var	$preTab = $('.pre-tab', $schemePopup),
      $t_head = $('.t_head', $part2);
        if ( !(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) ) {
            var constrainArray = function(){
                var wDiff = $map.width() - $parent.width();
                var hDiff = $map.height() - $parent.height();
                return [-hDiff, 0, 0, -wDiff]
            };
            var pepCall = function() {
                $map.pep({
                    constrainTo: constrainArray()
                });
            };
            pepCall();
            $(window).on('resize', function () {
                constrainArray();
                $.pep.unbind($map);
                pepCall();
            });
        } else {
            $parent.css('overflow', 'auto');
        }
    
    //Клик на здании
        $build.on('click', function(event) {
      event.preventDefault();
            var $thisBuild = $(this);
            $schemePopup.fadeIn(200);
            $thisBuild.addClass('active');
      //получаем данные json для конкретного дома
      //и запускает .part1 с параметрами из файла
      var $buildInfo = new Object();
      $buildInfo.numberBuild = $thisBuild.attr('class').split(' ');
      $buildInfo.numberBuild = $buildInfo.numberBuild[1];

      $.getJSON('json/houses.json', function(data) {
        var obj= data[$buildInfo.numberBuild];
        $buildInfo.name 			= 	obj.name,
        $buildInfo.count_sections 	= 	obj.count_sections,
        $buildInfo.count_floors 	= 	obj.count_floors,
        $buildInfo.count_apps 		= 	obj.count_apps,
        $buildInfo.count_1_apps 	= 	obj.count_1_apps,
        $buildInfo.count_2_apps 	= 	obj.count_2_apps,
        $buildInfo.count_3_apps 	= 	obj.count_3_apps,
        $buildInfo.count_4_apps 	= 	obj.count_4_apps,
        $buildInfo.end_date 		= 	obj.end_date,
        $buildInfo.type 			= 	obj.type;
      
        //Если не указано количество квартир, считаем, что информации по дому ещё нет.
        if ($buildInfo.count_apps=='' || $buildInfo.count_apps=='0') {
          $part1.hide();
          $part2.hide();					
          $part3.show();
          return false;
                } else {
          $part1.show();
          $part2.hide();
          $part3.hide();
        }
        
        //Планировки отображаются в зависимости от типа
        $t_head.data("type", $buildInfo.type);
        
        //Заполняем part1 инфой по домам
        $('#bld-name', $part1).html($buildInfo.name);
        $('.showplans', $part2).html($buildInfo.name);
        p = $('#build-info', $part1).find('p span');
        p.eq(0).html($buildInfo.count_sections);
        p.eq(1).html($buildInfo.count_floors);
        p.eq(2).html($buildInfo.count_apps);
        p.eq(3).html($buildInfo.end_date);
        
        li = $('#build-info', $part1).find('li span');
        li.eq(0).html($buildInfo.count_1_apps);
        li.eq(1).html($buildInfo.count_2_apps);
        li.eq(2).html($buildInfo.count_3_apps);
        
        //Показываем вкладки с планировками в зависимости от данных
        $preTab.css('display', 'inline-block');
        $preTab.css('width', '25%');
        if($buildInfo.count_4_apps == '0') {
          $preTab.eq(3).css('display', 'none');
          $preTab.eq(7).css('display', 'none');
          $preTab.css('width', '33%');
        }
        if($buildInfo.count_3_apps == '0') {
          $preTab.eq(2).css('display', 'none');
          $preTab.eq(6).css('display', 'none');
          $preTab.css('width', '50%');
        }
        if($buildInfo.count_2_apps == '0') {
          $preTab.eq(1).css('display', 'none');
          $preTab.eq(5).css('display', 'none');
          $preTab.css('width', '100%');
        }
        //Удаляем прежний owlCarousel
        var $flats_slider = $('.flats-slider')
        
        if ($flats_slider.hasClass("owl-carousel")) {
          $flats_slider.each(function() {
            $(this).empty();
            $(this).data('owlCarousel').destroy();
          });
        }				
        //Заполняем планировки---------------------------------
        switch ($buildInfo.type) {
          case 'CUBE':
            $flats_slider.eq(0).html(	'<a href="img/planes/CUBE/1/1.png"><img src="img/planes/mini/CUBE/1/1.png"></a>'+
                          '<a href="img/planes/CUBE/1/2.png"><img src="img/planes/mini/CUBE/1/2.png"></a>'+
                          '<a href="img/planes/CUBE/1/3.png"><img src="img/planes/mini/CUBE/1/3.png"></a>'+
                          '<a href="img/planes/CUBE/1/4.png"><img src="img/planes/mini/CUBE/1/4.png"></a>');
            $flats_slider.eq(1).html(	'<a href="img/planes/CUBE/2/1.png"><img src="img/planes/mini/CUBE/2/1.png"></a>'+
                          '<a href="img/planes/CUBE/2/2.png"><img src="img/planes/mini/CUBE/2/2.png"></a>'+
                          '<a href="img/planes/CUBE/2/3.png"><img src="img/planes/mini/CUBE/2/3.png"></a>'+
                          '<a href="img/planes/CUBE/2/4.png"><img src="img/planes/mini/CUBE/2/4.png"></a>');
            $flats_slider.eq(2).html(	'<a href="img/planes/CUBE/3/1.png"><img src="img/planes/mini/CUBE/3/1.png"></a>'+
                          '<a href="img/planes/CUBE/3/2.png"><img src="img/planes/mini/CUBE/3/2.png"></a>');
            break;                      
          case 'WALL':                    
            $flats_slider.eq(0).html(	'<a href="img/planes/WALL/1/1.png"><img src="img/planes/mini/WALL/1/1.png"></a>'+
                          '<a href="img/planes/WALL/1/2.png"><img src="img/planes/mini/WALL/1/2.png"></a>'+
                          '<a href="img/planes/WALL/1/3.png"><img src="img/planes/mini/WALL/1/3.png"></a>'+
                          '<a href="img/planes/WALL/1/4.png"><img src="img/planes/mini/WALL/1/4.png"></a>');
            $flats_slider.eq(1).html(	'<a href="img/planes/WALL/2/1.png"><img src="img/planes/mini/WALL/2/1.png"></a>'+
                          '<a href="img/planes/WALL/2/2.png"><img src="img/planes/mini/WALL/2/2.png"></a>'+
                          '<a href="img/planes/WALL/2/3.png"><img src="img/planes/mini/WALL/2/3.png"></a>'+
                          '<a href="img/planes/WALL/2/4.png"><img src="img/planes/mini/WALL/2/4.png"></a>'+
                          '<a href="img/planes/WALL/2/5.png"><img src="img/planes/mini/WALL/2/5.png"></a>'+
                          '<a href="img/planes/WALL/2/6.png"><img src="img/planes/mini/WALL/2/6.png"></a>');
            break;
        }
        //Открываем apps.json для получения информации о планировках
        $.getJSON('img/planes/'+$buildInfo.type+'/apps.json', function(AppsData) {
          //Прикручиваем magnificPopup
          $flats_slider.each(function(index) {
            var $h2room;
            switch (index) {
              case 0:	$h2room = "Однокомнатная"; break;
              case 1:	$h2room = "Двухкомнатная"; break;
              case 2:	$h2room = "Трехкомнатная"; break;
              case 3:	$h2room = "Четырехкомнатная"; break;							
            }
            $(this).magnificPopup({
              delegate: 'a', 
              type: 'image',
              gallery: {
                enabled: true,
                navigateByImgClick: true,
                arrowMarkup: '<button type="button" class="mfp-arrow mfp-arrow-%dir% fa fa-angle-%dir%"></button>'
              },
              image: {
                markup: '<div id="flats-content" class="mfp-figure">'+
                      '<div class="mfp-close"></div>'+
                      '<div class="iblock">'+
                        '<div class="mfp-img"></div>'+
                      '</div>'+
                      '<div class="iblock">'+
                        '<p class="pp-flat-head">'+
                          '<h1>Дом '+$buildInfo.name+'</h1>'+
                          '<h2>'+$h2room+' квартира <span></span></h2>'+
                        '</p>'+
                        '<p id="gen_area">Общая площадь: <span>15,45</span> м<sup>2</sup></p>'+
                        '<p id="area_w_b">Площадь без лоджии: <span>13,4</span> м<sup>2</sup></p>'+
                        '<p id="liv_area">Жилая площадь площадь: <span>8,68</span> м<sup>2</sup></p>'+
                        '<button id="button-mini" class="yellow-button mini">Оставить заявку</button>'+
                        '<p class="feedbackpls" style="display:none;">Эта кнопка пока не доступна.</p>'+
                        '<p class="feedbackpls" style="display:none;">Чтобы отправить заявку, воспользуйтесь, пожалуйста, формой внизу сайта.</p>'+
                        '<form id="mini-form" style="display:none;">'+
                        '<input type="text" placeholder="Ваше имя"/>'+
                        '<input type="tel" placeholder="Ваш телефон"/>'+
                        '<button id="submit" class="yellow-button mini">Отправить</button>'+
                        '<p id="mini-form-status"></p>'+
                        '</form>'+
                      '</div>'+								  
                    '</div>'		
              },
              overflowY: 'scroll',
              callbacks: {
                markupParse: function(template, values, item) {
                  var $splitsrc = item.src.split('/');
                  $index_plane = $splitsrc[4].split('.')[0];//Номер планировки
                  $count_room = $splitsrc[3]; //Количество комнат

                  $('h2 span',template).html(' №' + $index_plane);
                  var im = AppsData[$count_room+'_room'][$index_plane];

                  $('#gen_area span',template).text(im.gen_area);
                  $('#area_w_b span',template).text(im.area_w_b);
                  $('#liv_area span',template).text(im.liv_area);
                }
              }
            });
          });
          //Прикручиваем owlCarousel для добавленных элементов
          $flats_slider.owlCarousel({
            loop: true,
            margin: 30,
            items: 4,
            autoWidth: true
          });
        });
      });
      return false;
        });
    //Клик на планировки
    $('a.pre-tab').on('click', function() {
      //Переключение вкладки
      $('.t_head > div', $part2).eq($(this).index()).trigger('click');
      $part1.hide();			
      $part2.show();
      return false;
    });	
    },

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
v- death, 2015-11-29
@vGrabko99

here you go. But this code makes my eyes watery ..

Z
Zakharov Alexander, 2015-11-29
@AlexZaharow

If you do not delve into the business logic - summing up many lines with the "+" operation is not a good idea. I somehow "peeped" what happens in memory through a profiler with multi-cycle and multi-line additions - each "+" operation creates a separate line in memory, i.e. "a"+"b"+"c", then there will be two strings "ab" and "abc" in memory. Therefore, for large string additions, I use ["a", "b", "c"].join(""). Then the output will be a real connection in one line. And yes, this joke also happened to me in chrome, but after such optimization, other browsers also started working faster.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question