Javascript '$(document).ready()' 的非 jQuery 等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2304941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the non-jQuery equivalent of '$(document).ready()'?
提问by TIMEX
What is the non-jQuery equivalent of $(document).ready()?
什么是非 jQuery 等价物$(document).ready()?
采纳答案by Doug Neiner
The nice thing about $(document).ready()is that it fires before window.onload. The load function waits until everything is loaded, including external assets and images. $(document).ready, however, fires when the DOM tree is complete and can be manipulated. If you want to acheive DOM ready, without jQuery, you might check into this library. Someone extracted just the readypart from jQuery. Its nice and small and you might find it useful:
好的一点$(document).ready()是它之前会触发window.onload。加载函数会等待所有内容加载完毕,包括外部资源和图像。$(document).ready,但是,当 DOM 树完成并且可以被操作时触发。如果你想在没有 jQuery 的情况下实现 DOM 就绪,你可以查看这个库。有人只ready从 jQuery 中提取了一部分。它又好又小,你可能会发现它很有用:
回答by sospedra
This works perfectly, from ECMA
这非常有效,来自 ECMA
document.addEventListener("DOMContentLoaded", function() {
// code...
});
The window.onloaddoesn't equal to JQuery $(document).readybecause $(document).readywaits only to the DOM tree while window.onloadcheck all elements including external assets and images.
在window.onload不等于JQuery的$(document).ready,因为$(document).ready等待只对DOM树,同时window.onload检查,包括对外资产和图像的所有元素。
EDIT: Added IE8 and older equivalent, thanks to Jan Derk's observation. You may read the source of this code on MDN at this link:
编辑:由于Jan Derk的观察,添加了 IE8 和更旧的等效版本。您可以通过以下链接在 MDN上阅读此代码的来源:
// alternative to DOMContentLoaded
document.onreadystatechange = function () {
if (document.readyState == "interactive") {
// Initialize your application or run some code.
}
}
There are other options apart from "interactive". See the MDNlink for details.
除了 ,还有其他选择"interactive"。有关详细信息,请参阅MDN链接。
回答by Thank you
A little thing I put together
我放在一起的小东西
domready.js
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);
How to use it
如何使用它
<script src="domready.js"></script>
<script>
domReady(function(event) {
alert("dom is ready!");
});
</script>
You can also change the context in which the callback runs by passing a second argument
您还可以通过传递第二个参数来更改回调运行的上下文
function init(event) {
alert("check the console");
this.log(event);
}
domReady(init, console);
回答by CTS_AE
Now that it's 2018 here's a quick and simple method.
现在是 2018 年,这里有一个快速简单的方法。
This will add an event listener, but if it already fired we'll check that the dom is in a ready state or that it's complete. This can fire before or after sub-resources have finished loading (images, stylesheets, frames, etc).
这将添加一个事件侦听器,但如果它已经被触发,我们将检查 dom 是否处于就绪状态或是否已完成。这可以在子资源(图像、样式表、框架等)加载完成之前或之后触发。
function domReady(fn) {
// If we're early to the party
document.addEventListener("DOMContentLoaded", fn);
// If late; I mean on time.
if (document.readyState === "interactive" || document.readyState === "complete" ) {
fn();
}
}
domReady(() => console.log("DOM is ready, come and get it!"));
Additional Readings
附加阅读
- https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
- https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
- https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
- https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
Update
更新
Here's some quick utility helpers using standard ES6 Import & Export I wrote that include TypeScript as well. Maybe I can get around to making these a quick library that can be installed into projects as a dependency.
这里有一些使用我编写的标准 ES6 导入和导出的快速实用程序助手,其中也包括 TypeScript。也许我可以让这些快速库作为依赖项安装到项目中。
JavaScript
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);
}
}
TypeScript
打字稿
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);
}
}
Promises
承诺
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);
}
});
回答by online Thomas
According to http://youmightnotneedjquery.com/#readya nice replacement that still works with IE8 is
根据http://youmightnotneedjquery.com/#ready,一个仍然适用于 IE8 的不错的替代品是
function ready(fn) {
if (document.readyState != 'loading') {
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading')
fn();
});
}
}
// test
window.ready(function() {
alert('it works');
});
improvements: Personally I would also check if the type of fnis a function.
And as @elliottregansuggested remove the event listener after use.
改进:我个人也会检查类型fn是否为函数。正如@elliottregan建议在使用后删除事件侦听器一样。
The reason I answer this question late is because I was searching for this answer but could not find it here. And I think this is the best solution.
我回答这个问题晚的原因是因为我正在寻找这个答案,但在这里找不到。我认为这是最好的解决方案。
回答by Zigri2612
There is a standards based replacement,DOMContentLoaded that is supported by over 90%+ of browsers, but not IE8 (So below code use by JQuery for browser support):
有一个基于标准的替代品,DOMContentLoaded 被超过 90% 的浏览器支持,但不支持 IE8(所以下面的代码被 JQuery 用于浏览器支持):
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
jQuery's native functionis much more complicated than just window.onload, as depicted below.
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 );
}
回答by Brian Campbell
In plain vanilla JavaScript, with no libraries? It's an error. $is simply an identifier, and is undefined unless you define it.
在没有库的普通 JavaScript 中?这是一个错误。$只是一个标识符,除非你定义它,否则它是未定义的。
jQuery defines $as it's own "everything object" (also known as jQueryso you can use it without conflicting with other libraries). If you're not using jQuery (or some other library that defines it), then $will not be defined.
jQuery 定义$为它自己的“所有对象”(也称为jQuery这样,您可以在不与其他库冲突的情况下使用它)。如果您没有使用 jQuery(或其他定义它的库),则$不会被定义。
Or are you asking what the equivalent is in plain JavaScript? In that case, you probably want window.onload, which isn't exactly equivalent, but is the quickest and easiest way to get close to the same effect in vanilla JavaScript.
或者你在问普通 JavaScript 中的等价物是什么?在这种情况下,您可能想要window.onload,它并不完全等效,但它是在 vanilla JavaScript 中接近相同效果的最快和最简单的方法。
回答by NVRM
The easiest way in recent browsers would be to use the appropriate GlobalEventHandlers, onDOMContentLoaded, onload, onloadeddata(...)
最近浏览器中最简单的方法是使用适当的GlobalEventHandlers、onDOMContentLoaded、onload、onloadeddata(...)
onDOMContentLoaded = (function(){ console.log("DOM ready!") })()
onload = (function(){ console.log("Page fully loaded!") })()
onloadeddata = (function(){ console.log("Data loaded!") })()
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
DOMContentLoaded 事件在初始 HTML 文档完全加载和解析后触发,无需等待样式表、图像和子框架完成加载。一个非常不同的事件加载应该只用于检测完全加载的页面。在 DOMContentLoaded 更合适的地方使用 load 是一个非常流行的错误,所以要小心。
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
The function used is an IIFE, very useful on this case, as it trigger itself when ready:
使用的函数是一个 IIFE,在这种情况下非常有用,因为它在准备好时触发自己:
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
It is obviously more appropriate to place it at the end of any scripts.
将它放在任何脚本的末尾显然更合适。
In ES6, we can also write it as an arrow function:
在 ES6 中,我们也可以把它写成一个箭头函数:
onload = (() => { console.log("ES6 page fully loaded!") })()
The best is to use the DOM elements, we can wait for any variable to be ready, that trigger an arrowed IIFE.
最好是使用 DOM 元素,我们可以等待任何变量准备好,触发一个带箭头的 IIFE。
The behavior will be the same, but with less memory impact.
行为将相同,但对内存的影响较小。
footer = (() => { console.log("Footer loaded!") })()
<div id="footer">
In many cases, the documentobject is also triggering when ready, at least in my browser. The syntax is then very nice, but it need further testings about compatibilities.
在许多情况下,文档对象在 ready 时也会触发,至少在我的浏览器中是这样。语法非常好,但它需要进一步测试兼容性。
document=(()=>{ /*Ready*/ })()
回答by joan16v
The body onLoad could be an alternative too:
主体 onLoad 也可以是一个替代方案:
<html>
<head><title>Body onLoad Exmaple</title>
<script type="text/javascript">
function window_onload() {
//do something
}
</script>
</head>
<body onLoad="window_onload()">
</body>
</html>

