我有一个第三方脚本,在我的网页上加载一个图片库的图片来自外地。
我的页面开头是空的:
<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()之后,也会有多个命令发送给.galleria_image和observer.disconnect()。
所以我用underscore代替了:
// create an observer instance
var observer = new MutationObserver(function(mutations) {
var loaded = _.find(mutations, function(mutation){
console.log("observer running");
return mutation.target.className === "galleria-image";
});
if(loaded){
Blaze.remove(loadingView);
observer.disconnect();
console.log("observer stopped");
};
});发布于 2016-03-16 01:24:04
有一个选项可以让您做您想做的事情:观察元素的子树。只需将subtree: true添加到用于MutationObserver的config中即可。
// ...
// In this case case only these two are needed, I believe.
var config = {
childList: true,
subtree: true
};
// ...observe这应该允许您显示何时插入了.gallaria_images。另外,您(OP)还应该再次检查在发生这种情况时是否加载了图像。
https://stackoverflow.com/questions/36025159
复制相似问题