javascript:如何写$(document).ready就像没有jquery的事件

在jquery $(document).ready(function)或者$(function)中,我怎样才能在没有jquery的情况下做同样的事情,我需要浏览器兼容,并允许附加多个函数。

注意:dom ready!= window onload

这是jQuery包装你正在寻找的function的方式 – 这个片段不需要jQuery,并且是跨浏览器兼容的。 我用你的callbackreplace了所有的jQuery.ready() yourcallback – 你需要定义。

这里发生了什么:

  • 首先,定义DOMContentLoaded函数,当DOMContentLoaded事件触发时,将使用该函数 – 它确保callback只被调用一次。
  • 检查文档是否已经加载 – 如果是,立即发起callback
  • 否则嗅探function( document.addEventListener / document.attachEvent )并将callback绑定到它(IE和普通浏览器不同,再加上onloadcallback)

从jQuery 1.4.3中解除了函数bindReady()和DOMContentLoaded :

 /* * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ // Cleanup functions for the document ready method // attached in the bindReady handler if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); //jQuery.ready(); yourcallback(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); //jQuery.ready(); yourcallback(); } }; } // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready //return setTimeout( jQuery.ready, 1 ); // ^^ you may want to call *your* function here, similarly for the other calls to jQuery.ready setTimeout( yourcallback, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work //window.addEventListener( "load", jQuery.ready, false ); window.addEventListener( "load", yourcallback, 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", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent( "onload", yourcallback ); } 

这是51行纯JavaScript代码,只是为了可靠地注册事件。 据我所知,没有更简单的方法。 看看像jQuery这样的包装器是什么样子的:它们包装了能力嗅探和丑陋的兼容性问题,以便您可以专注于其他方面。

最小的DOMReady代码,永远。

 <html> <head> <script> var ready = function (f) { (/complete|loaded|interactive/.test(document.readyState)) ? f() : setTimeout(ready, 9, f); }; </script> </head> <body> <script> ready(function () { alert('DOM Ready!'); }); </script> </body> </html> 

如果您支持IE9 +和现代(2013)版本的Chrome,FF,Safari等,则可以使用这一切。

 function ready(event) { // your code here console.log('The DOM is ready.', event); // clean up event binding window.removeEventListener('DOMContentLoaded', ready); } // bind to the load event window.addEventListener('DOMContentLoaded', ready); 

这是我使用的一种方法,似乎可靠地工作

 function ready(func) { var span = document.createElement('span'); var ms = 0; setTimeout(function() { try { document.body.appendChild(span); document.body.removeChild(span); //Still here? Then document is ready func(); } catch(e) { //Whoops, document is not ready yet, try again... setTimeout(arguments.callee, ms); } }, ms); } 

很简单,它只是试图将一个空的<span>元素附加到document.body 。 如果文档不是“就绪”,则会抛出exception,在这种情况下,它会再次尝试使用新的setTimeout调用。 一旦抛出exception,就调用callback函数。

我很乐意听到这个方法是否有问题。 它对我来说工作得很好,但是我没有做任何stream行的Javascript框架的自然testing。

我已经看到很多不同的方式来尝试这样做。 最简单的方法(我认为最初是由yahoobuild议的)就是在close body标签之后调用你的初始化函数,这有点突兀,但它是一行代码。

编辑

DomReady事件在JavaScript中不存在。 您可以通过执行像迪安·爱德华兹(Dean Edwards)这样的人在这里和在这里完成的一些精彩的工作来实现您自己,在那里您可以在文档而不是窗口上执行类似的事件附件过程。


查看user83421的答案如何在Javascript中添加一个额外的window.onload事件

这里也重述一下。

 if (window.addEventListener) // W3C standard { window.addEventListener('load', myFunction, false); // NB **not** 'onload' } else if (window.attachEvent) // Microsoft { window.attachEvent('onload', myFunction); } 

我在'close body'标签之后和'close html'标签之前有这个。 它工作得很好。 加载预设function将宽度,高度和位置值分配给css div标签。 用于不同的屏幕尺寸。

 document.onreadystatechange = function () { if (document.readyState == "interactive") { loadPresets(); } 

}