等待元素显示本机javascript

时间:2017-12-26 17:56:14

标签: javascript javascript-events mutation-observers

基于这个Q&A,我尝试编写一些本地JS代码(不使用库),这些代码将具有元素添加层次结构/依赖性,这意味着我必须等待一些元素到在我继续使用该功能之前显示/加载。我有以下函数来创建和使用MutationObservers来跟踪DOM更改:

/**
 * Creates an observer that tracks added DOM elements and executes a function when they're added 
 * @param {HTMLElement} observedObject - the dom element to observe
 * @param {Function} elementFunc - the function to execute when elements are added
 * @param {Number} timeoutMs - the amount of miliseconds to wait before disconnecting the observer
 */
function observeDOM(observedObject, elementFunc, timeoutMs) {
  var connected = false;
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (!mutation.addedNodes) return
      for (var i = 0; i < mutation.addedNodes.length; i++) {
        if(elementFunc(mutation.addedNodes[i])) {
          // disconnect when the function returns true 
          observer.disconnect();
          break;
        }
      }
    })
  });

  observer.observe(observedObject, {
      childList: true
    , subtree: true
    , attributes: false
    , characterData: false
  });
  connected = true;

  // disconnect the observer after N seconds
  if(timeoutMs >= 0) {
    setTimeout(function() {
      if(connected) {
        observer.disconnect();
        connected = false;
      }
    }, timeoutMs);  
  }
}

我使用上面的函数:

// do some staff...
observeDOM(document.body, function(node) {
  if(node.className === "class1") {
    // do some staff and wait for another element 
    observeDOM(document.body, function(node) {
      if(node.className === "class2") {
        // do some staff and wait for another element 
        observeDOM(document.body, function(node) {
          if(node.className === "class2") {
            //[...]
            return true;
          }
          return false;
        }
        return true;
      }
      return false;
    }
    return true; // stop the observer
  }
  return false; // go on listening to elements addition
} 

您认为有更优雅的方式来实现它吗?最让我眼前一亮的是当我有大量元素要等待时,我会创建嵌套块的音调

0 个答案:

没有答案