Skip to content

Instantly share code, notes, and snippets.

@yuanoook
Last active October 20, 2018 11:19
Show Gist options
  • Save yuanoook/ec494a2a26b7d5eabc872f28a4dfb9f2 to your computer and use it in GitHub Desktop.
Save yuanoook/ec494a2a26b7d5eabc872f28a4dfb9f2 to your computer and use it in GitHub Desktop.
HI = window.HI || {}
HI.waitMS = async ms => new Promise(resolve => setTimeout(resolve, ms))
HI.loadJS = (src, call) => {
var script = document.createElement('script')
script.src = src // + '?_t=' + Date.now()
script.onload = call
document.head.appendChild(script)
}
HI.loadJSArr = (srcArr, call) => {
if (srcArr.length) {
HI.loadJS(srcArr.shift(), () => HI.loadJSArr(srcArr, call))
} else {
call && call()
}
}
HI.monitor = (() => {
const monitoringPool = []
const monitor = (monitorCase) => {
monitoringPool.push({
startAt: Date.now(),
...monitorCase
})
let cancelMonitor = () => {
let index = monitoringPool.index(monitorCase)
index >= 0 && monitoringPool.splice(index, 1)
}
return cancelMonitor
}
const startMonitoring = () => {
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
const loop = async (s, call) => {
while(true) {
await wait(s)
if(!call()) break
}
}
loop(1000, () => {
for (let i = monitoringPool.length - 1; i >= 0; i--) {
let monitorCase = monitoringPool[i]
let {condition, call, once = true, startAt, timeout, timeoutCall} = monitorCase
let conditionResult = typeof condition === 'function' ? condition() : condition
if (conditionResult) {
call(conditionResult)
once && monitoringPool.splice(i, 1)
}
if (timeout && timeout < (Date.now() - startAt)) {
timeoutCall && timeoutCall(`Timeout ${timeout}ms`)
monitoringPool.splice(i, 1)
}
}
return true
})
}
startMonitoring()
return monitor
})()
HI.waitSelector = (selector, call) => {
const getDom = () => $(selector)
HI.monitor({
condition: () => getDom().length && getDom(),
call
})
}
HI.loadJS('https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js')
HI.ready = call => {
HI.monitor({
condition: () => document && document.documentElement && window.$,
call
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment