Simple Wait For Document Helper

A Simple helper library for wait document load

Questo script non dovrebbe essere installato direttamente. È una libreria per altri script da includere con la chiave // @require https://update.greasyfork.org/scripts/373524/639009/Simple%20Wait%20For%20Document%20Helper.js

/**
 * Simple Wait For Document Helper
 * by Jixun<https://jixun.moe/>
 */
var waitForDocument = (function () {
  var callbackQueue = []
  var ready = false

  function waitForDocument(callback) {
    if (ready) {
      requestAnimationFrame(callback)
      return
    }

    callbackQueue.push(callback)
  }

  function triggerCallbackQueue() {
    if (ready === true) {
      // Already processed
      return
    }

    ready = true

    // process callback queue
    callbackQueue.forEach(requestAnimationFrame)
    callbackQueue = null

    // remove those listeners
    document.removeEventListener('DOMContentLoaded', triggerCallbackQueue)
    document.removeEventListener('load', triggerCallbackQueue)
  }

  // listen for document loaded events
  document.addEventListener('DOMContentLoaded', triggerCallbackQueue)
  document.addEventListener('load', triggerCallbackQueue)

  // check if document is ready yet
  if (['interactive', 'complete'].indexOf(document.readyState) !== -1) {
    triggerCallbackQueue()
  }

  return waitForDocument
})()