MutationObserver没有显示所有突变?

时间:2016-03-16 01:15:19

标签: javascript jquery

我有一个第三方脚本,可以在我的网页上加载照片库,图片来自异地。

我的页面空白:

  <div class="container-fluid" id="cincopa">

  </div>

第三方脚本然后添加其他内容(如照片库的框架):

      <div class="container-fluid" id="cincopa">
        <div id="cp_widget_38cc1320-f4a4-407a-a80e-1747bd339b64">

        </div>
      </div>

然后最终图片加载:

      <div class="container-fluid" id="cincopa">
        <div id="cp_widget_38cc1320-f4a4-407a-a80e-1747bd339b64">
          <div class="galleria_images">
            <div class="galleria_image">SomeImage</div>
            <div class="galleria_image">SomeImage</div>
            <div class="galleria_image">SomeImage</div>
          </div>
        </div>
      </div>

我想:

  • 显示加载动画

  • MutationObserver

  • 上设置$('#cincopa')
  • 当检测到$('.galleria_image')已创建时,表示已加载图片,因此我可以

  • 删除加载动画

代码:

var target = document.querySelector('#cincopa');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
    console.log(mutations);
    mutations.forEach(function(mutation) {
      console.log(mutation.type);
    }); 
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// start the observer, pass in the target node, as well as the observer options
observer.observe(target, config);

问题是仅MutationObserver控制台记录一个突变,而MutationRecord只有一个突变。我希望有很多突变,因为第三方脚本会创建DOM元素。

我误解了MutationObserver的工作原理吗?

以下是解决方案

// This is MeteorJS creating the loading spinning thing
var loadingView = Blaze.render(Template.loading, $('#cincopa')[0]);

// select the target node
var target = document.querySelector('#cincopa');

// create an observer instance
var observer = new MutationObserver(function(mutations) {

  mutations.forEach(function(mutation) {
    if(mutation.target.className === "galleria_image"){
        // a image has been loaded, so remove the loading spinner and 
        // kill the observer
        Blaze.remove(loadingView);
        observer.disconnect();
    }
  }); 

});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true, subtree: true };

// start the observer, pass in the target node, as well as the observer options
observer.observe(target, config);

更新解决方案

.forEach是愚蠢的,并没有很好的方法来摆脱循环,这意味着即使在{{Blaze.remove()observer.disconnect()之后,我也会收到多个命令已找到1}}。

所以我改为使用.galleria_image

underscore

1 个答案:

答案 0 :(得分:2)

有一个选项可以让你完全按照自己的意愿行事:观察元素的子树。只需将subtree: true添加到<a href="#"...的{​​{1}}。

config

这应该允许您计算何时插入MutationObserver。作为旁注,您(OP)还应该仔细检查图像是否在发生时加载。