Jquery初始化混乱

时间:2016-02-24 00:39:29

标签: javascript jquery

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

            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
                //[...]
            }

这可能是什么目的?或者是胡说八道?

1 个答案:

答案 0 :(得分:2)

代码确保调用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
            //[...]
        }