我正在尝试寻找YUI事件实用程序的替代者。当前的YUI代码:
YAHOO.util.Event.onAvailable('elementId', function(){}
我尝试过的替代品
$(document).ready(function(){}
答案 0 :(得分:0)
非常基本,但这可以代替您的等待位置。
监视DOM突变可能比仅每40毫秒检查一次更好。
// This is dummy code, will add an element after 3secs
setTimeout(() => {
const div = document.createElement('div');
div.classList.add('the-div');
div.innerText = 'I have arrived!';
document.querySelector('.container').appendChild(div);
}, 3000);
// This is the method.
const ready = (cssSelector, func) => {
// Try and get our element.
const el = document.querySelector(cssSelector);
if(el) {
// If we find it, execute the callback
func(el);
} else {
// Not there yet.
setTimeout(() => ready(cssSelector, func), 40);
}
}
ready('.the-div', (el) => {
console.log(el);
document.querySelector('.notify').innerText = 'Found our element!';
});
// Not for me, but :)
document.whenAvailable = ready;
document.whenAvailable('.the-div', () => console.log('Another Way!!'));
<div class="container"></div>
<div class="notify">Waiting</div>
在这里与MutationObserver合作可能是一个非常好的选择。