mutation observer for a particular div

Viewed 1243

I have around a large html data, around 200k data with sub details images and all.

The problem i am facing when i try to set the html content that i get, i am getting browser stuck issue. So what i am trying to do is i am writing an observer which checks for that particular div, whether all the html has been added. Then i need to disable the loader so the user can use

What i have tried so far

var isHtmlAppending = true



function mutate(mutations) {
  mutations.forEach(function(mutation, index) {
    if(index === mutations.length - 1){
      isHtmlAppending = false
   }
  });
}


  var target = document.getElementById('container')
  var observer = new MutationObserver( mutate );
  var config = { characterData: true, attributes: false, childList: false, 
  subtree: true };

  observer.observe(target, config);



$.ajax({
  // call the api and get the html data
  success: (function(data){
     $("#container").html = data.renderedHtml
  })
})

How to make this working ?, any help appreciated

1 Answers

The childList property in the config must be set to true in order to find new elements added.

Here's how you can use the MutationObserver to find the element that you are looking for:

var target = document.getElementById("target");
var numDivs = 0;

var btn = document.getElementById("add-div");
btn.addEventListener("click", function() {
  var newDiv = document.createElement("div");
  newDiv.id = "new-div-" + numDivs;
  newDiv.innerHtml = "New Div";
  target.appendChild(newDiv);
  numDivs++;
});

var mo = new MutationObserver(function(list, _o) {
  var numItems = list.length;
  for (var i = 0; i < numItems; i++) {
    var m = list[i];
    if (m.type === "childList") {
      var node = m.addedNodes[0];
      if (node.id == "new-div-0") { // Example target id
        console.log("I found the element I was looking for!");
      }
    }
  }
});

mo.observe(target, {
  childList: true
});
#target>div {
  background: #a33;
  margin: 2px 0;
  width: 30px;
  height: 30px;
}
<div id="target">
  <button id="add-div">Add div</button>
</div>

Related