非jquery的$(document).ready()等价于什么?
当前回答
根据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'); });
我之所以回答这个问题晚,是因为我一直在寻找这个答案,但在这里找不到。我认为这是最好的解决办法。
其他回答
根据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'); });
我之所以回答这个问题晚,是因为我一直在寻找这个答案,但在这里找不到。我认为这是最好的解决办法。
这从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文档。
有一个基于标准的替换
超过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 );
}
这没有回答问题,也没有显示任何非jquery代码。请看下面@ sospedra的回答。
$(document).ready()的优点是它在window.onload之前触发。load函数等待加载所有内容,包括外部资产和图像。美元(文档)。但是,当DOM树完成并且可以操作时,ready将被触发。如果你想在没有jQuery的情况下实现DOM,你可以查看这个库。有人从jQuery中提取了现成的部分。它又小又漂亮,你可能会发现它很有用:
domready at谷歌Code
我拼凑的一个小东西
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);