Jagrut February 2016

Page becomes unresponsive after some time

I have a problem with my jQuery/Javascript code. All works as expected but after some time the page becomes unresponsive throwing the Unresponsive Script error for jQuery. I am using a jQuery Library for displaying lists as coverflow.

Also, after all calls to backend I have to refresh the particular div and hence I destroy and recreate the div every time the call is made to backend.

Please let me know what is the problem in the structure of the code given below:

(Please note this is just a snippet with important methods. All these methods also have other logic written in them which is not displayed here).

function showAllData(dataFromServer) {
  $('#child').remove();
  $('#parent').append($('<div id="child"></div>'));

  $.each(dataFromServer.someArray, function(index, item) {
    var html = '<li>' + item + '</li>';
    $('#child').append($(html));
  });

  //Attach Event to div
  $("#child").on("click", function() {
    removeTag();
  });
};

$(document).ready(function() {
  //got data from server(Spring MVC) in a var 'dataFromServer'
  //code not written here
  showAllData(dataFromServer);
  $("#child").flipster(); //a coverflow library	
});


$(document).on('submit', '#formSubmit', function(event) {
  event.preventDefault();
  $.ajax({
    url: url,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: true,
    cache: false,
    data: JSON.stringify({
      dataFromClient: dataFromServer
    }),
    type: "POST",
    success: function(data) {
      dataFromServer = data;
      showAllData(dataFromServer);
      $("#child").flipster();
    },
    error: function(xhr, status, error) {
      console.log(xhr.r        

Answers


Lesley February 2016

You have some recursion going on which is exponentially adding #child .click() handlers. I have made this jsFiddle to simplify your code and demo what's going on. Open the console, click 'submit' to start, then click a few times on one of the list items. You'll see for each click, the console outputs more and more lines.

Try moving $("#child").on("click"...){} outside of function showAllData(){}

Update: So that the handler works after you remove and re-add #child you can add the click listener like this:

$('#parent').on('click', '#child', function() {
    // 
});

I've put this in an updated jsFiddle.

Update 2: I saw that Flipster was not re-initialising after you refresh #child and came up with this:

Change $("#child").flipster(); to $("#parent").flipster();. Then after doing $('#child').remove() in showAllData():

// remove the flipster classes from #parent or flipster will not re-initialise when called next time.
$('#parent').removeClass('flipster').removeClass(function(index, css) {
    return (css.match(/(^|\s)flipster-\S+/g) || []).join(' ');
});

I put this in a codePen.

Post Status

Asked in February 2016
Viewed 3,765 times
Voted 7
Answered 1 times

Search




Leave an answer