gpt4 book ai didi

javascript - jquery初始化困惑

转载 作者:行者123 更新时间:2023-11-29 21:33:13 24 4
gpt4 key购买 nike

现在无论出于何种原因,原作者在初始化时做了一些我不太理解的事情。这段代码在我看来是多余的:

            if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, false);
}
(function() {
/*@cc_on
try {
document.body.doScroll('up');
return init();
} catch(e) {}
/*@if (false) @*/
if (/loaded|complete/.test(document.readyState)) return init();
/*@end @*/
if (!init.done) setTimeout(arguments.callee, 30);
})();
if (window.addEventListener) {
window.addEventListener('load', init, false);
} else if (window.attachEvent) {
window.attachEvent('onload', init);
}

function init()
{
if (arguments.callee.done) return;
arguments.callee.done = true;
// do your thing
//[...]
}

这样做的目的是什么?还是胡说八道?

最佳答案

代码确保 init() 函数被调用。

它将 init 函数绑定(bind)到在加载 DOM 或页面时触发的事件监听器。

如果 readyState 确定这些事件已经触发,那么它会直接调用 init,否则它会每 30 毫秒检查一次 readyState。

        // Call init function when DOM is loaded
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, false);
}

// Immediately invoked function expression that calls init
// function if doScroll method does not throw error.
(function() {

try {
document.body.doScroll('up');
return init();
} catch(e) {}

// Call init function if DOMContentLoaded event has already been
// fired or if page is already loaded.
if (/loaded|complete/.test(document.readyState)) return init();

// arguments.callee is a reference to it's executing function
// which is this immediately invoked function expression.
// It will keep calling it every 30 milliseconds while init
// has not been called yet.
if (!init.done) setTimeout(arguments.callee, 30);
})();


// Call init function when window is loaded.
// `load` event is fired after DOMContentReady, when
// everything has loaded in the page.
if (window.addEventListener) {
window.addEventListener('load', init, false);

// Same as above but for IE versions 8 or less
} else if (window.attachEvent) {
window.attachEvent('onload', init);
}

function init() {
// If init has been called then immediately return.
if (arguments.callee.done) return;

// Set flag on itself to indicate that it init been called.
arguments.callee.done = true;
// do your thing
//[...]
}

关于javascript - jquery初始化困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35591139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com