非jquery的$(document).ready()等价于什么?


当前回答

有一个基于标准的替换

超过90%以上的浏览器支持DOMContentLoaded,但不是 IE8(以下代码由JQuery提供浏览器支持)

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

jQuery的本地函数比window复杂得多。Onload,如下所示。

function bindReady(){
    if ( readyBound ) return;
    readyBound = true;

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){
            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
            jQuery.ready();
        }, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {
        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );
                jQuery.ready();
            }
        });

        // If IE and not an iframe
        // continually check to see if the document is ready
        if ( document.documentElement.doScroll && window == window.top ) (function(){
            if ( jQuery.isReady ) return;

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch( error ) {
                setTimeout( arguments.callee, 0 );
                return;
            }

            // and execute any waiting functions
            jQuery.ready();
        })();
    }

    // A fallback to window.onload, that will always work
    jQuery.event.add( window, "load", jQuery.ready );
}

其他回答

现在是2018年,这里有一个快速而简单的方法。

这将添加一个事件监听器,但如果它已经被触发,我们将检查dom是否处于就绪状态或它是否完整。这可以在子资源完成加载(图像、样式表、框架等)之前或之后触发。

函数domReady(fn) { //如果我们到派对早 文档。addEventListener(“DOMContentLoaded”内,fn); //如果迟到;我的意思是准时。 如果文档。readyState === "interactive" ||文档。readyState === "complete") { fn (); } } domReady(() => console.log("DOM准备好了,来拿吧!"));

额外的数据

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded 检查加载是否已经完成 https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState


更新

下面是一些使用我编写的标准ES6导入和导出的快速实用工具,也包括TypeScript。也许我可以让这些快速库可以安装到项目作为一个依赖。

JavaScript

export const domReady = (callBack) => {
  if (document.readyState === "loading") {
    document.addEventListener('DOMContentLoaded', callBack);
  }
  else {
    callBack();
  }
}

export const windowReady = (callBack) => {
  if (document.readyState === 'complete') {
    callBack();
  }
  else {
    window.addEventListener('load', callBack);
  }
}

打印稿

export const domReady = (callBack: () => void) => {
  if (document.readyState === "loading") {
    document.addEventListener('DOMContentLoaded', callBack);
  }
  else {
    callBack();
  }
}

export const windowReady = (callBack: () => void) => {
  if (document.readyState === 'complete') {
    callBack();
  }
  else {
    window.addEventListener('load', callBack);
  }
}

承诺

export const domReady = new Promise(resolve => {
  if (document.readyState === "loading") {
    document.addEventListener('DOMContentLoaded', resolve);
  }
  else {
    resolve();
  }
});

export const windowReady = new Promise(resolve => {
  if (document.readyState === 'complete') {
    resolve();
  }
  else {
    window.addEventListener('load', resolve);
  }
});

我拼凑的一个小东西

domready.js

(function(exports, d) {
  function domReady(fn, context) {

    function onReady(event) {
      d.removeEventListener("DOMContentLoaded", onReady);
      fn.call(context || exports, event);
    }

    function onReadyIe(event) {
      if (d.readyState === "complete") {
        d.detachEvent("onreadystatechange", onReadyIe);
        fn.call(context || exports, event);
      }
    }

    d.addEventListener && d.addEventListener("DOMContentLoaded", onReady) ||
    d.attachEvent      && d.attachEvent("onreadystatechange", onReadyIe);
  }

  exports.domReady = domReady;
})(window, document);

如何使用

<script src="domready.js"></script>
<script>
  domReady(function(event) {
    alert("dom is ready!");
  });
</script>

您还可以通过传递第二个参数来更改回调运行的上下文

function init(event) {
  alert("check the console");
  this.log(event);
}

domReady(init, console);

这从ECMA完美地工作。这段代码是您所需要的全部内容,但如果您想挖掘更多内容并探索其他选项,请查看这段详细的解释。

document.addEventListener("DOMContentLoaded", function() {
  // code...
});

窗外。onload不等于JQuery $(document)。因为$(document)。ready只等待DOM树while窗口。Onload检查所有元素,包括外部资产和图像。

编辑:由于Jan Derk的观察,添加了IE8和更老的版本。您可以在MDN上阅读此代码的源代码:

// alternative to DOMContentLoaded
document.onreadystatechange = function () {
    if (document.readyState == "interactive") {
        // Initialize your application or run some code.
    }
}

除了“互动性”,还有其他选择。详见MDN文档。

根据http://youmightnotneedjquery.com/#ready的说法,一个很好的替代品仍然适用于IE8

函数准备(fn) { 如果文档。readyState != 'loading') { fn (); } else if (document.addEventListener) { 文档。addEventListener (DOMContentLoaded”内,fn); }其他{ 文档。attachEvent('onreadystatechange', function() { 如果文档。readyState != 'loading') fn (); }); } } / /测试 window.ready(函数(){ alert('它'); });

改进:我个人也会检查fn的类型是否为函数。 正如@elliottregan建议的那样,在使用后删除事件侦听器。

function ready(fn) { if (typeof fn !== 'function') { throw new Error('Argument passed to ready should be a function'); } if (document.readyState != 'loading') { fn(); } else if (document.addEventListener) { document.addEventListener('DOMContentLoaded', fn, { once: true // A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked. }); } else { document.attachEvent('onreadystatechange', function() { if (document.readyState != 'loading') fn(); }); } } // tests try { window.ready(5); } catch (ex) { console.log(ex.message); } window.ready(function() { alert('it works'); });

我之所以回答这个问题晚,是因为我一直在寻找这个答案,但在这里找不到。我认为这是最好的解决办法。

这没有回答问题,也没有显示任何非jquery代码。请看下面@ sospedra的回答。

$(document).ready()的优点是它在window.onload之前触发。load函数等待加载所有内容,包括外部资产和图像。美元(文档)。但是,当DOM树完成并且可以操作时,ready将被触发。如果你想在没有jQuery的情况下实现DOM,你可以查看这个库。有人从jQuery中提取了现成的部分。它又小又漂亮,你可能会发现它很有用:

domready at谷歌Code