Jquery 初始化混淆

Jquery initialization confusion

本文关键字:初始化 Jquery      更新时间:2023-09-26

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

            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 函数绑定到加载 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
            //[...]
        }