BigTSDMB / onElement

// ==UserScript==
// @exclude       *
// @namespace     BigTSDMB
// @author        BigTSDMB
// @name          $LIBRARY onElement


// ==UserLibrary==
// @name          onElement
// @description   Fires a callback function when a selected element arrives
// @license       MIT
// @version       1.0

// ==/UserScript==

// ==/UserLibrary==
function onElement(selector, callback, persistent, observerOptions) {
  if (!observerOptions) { observerOptions = { childList:true, subtree: true }; }
  let elementArrival = new MutationObserver( ()=>{
    let elements = document.querySelectorAll(selector);
    if (elements.length) {
      if (!persistent) { elementArrival.disconnect(); }
      callback(elements[0], elements);
    }
  }); elementArrival.observe(document, observerOptions);
}