Javascript window.onload vs $(document).ready()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3698200/
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
window.onload vs $(document).ready()
提问by Vaibhav Jain
What are the differences between JavaScript's window.onloadand jQuery's $(document).ready()method?
JavaScriptwindow.onload和 jQuery 的$(document).ready()方法有什么区别?
采纳答案by Guffa
The readyevent occurs after the HTML document has been loaded, while the onloadevent occurs later, when all content (e.g. images) also has been loaded.
该ready事件发生在 HTML 文档被加载之后,而该onload事件发生在之后,当所有内容(例如图像)也已经被加载时。
The onloadevent is a standard event in the DOM, while the readyevent is specific to jQuery. The purpose of the readyevent is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
该onload事件是 DOM 中的标准事件,而该ready事件是特定于 jQuery 的。该ready事件的目的是它应该在文档加载后尽早发生,以便为页面中的元素添加功能的代码不必等待所有内容加载完毕。
回答by Piskvor left the building
window.onloadis the built-in JavaScript event, but as its implementation had subtlequirks across browsers (Firefox, Internet Explorer 6, Internet Explorer 8, and Opera), jQuery provides document.ready, which abstracts those away, and fires as soon as the page's DOM is ready (doesn't wait for images, etc.).
window.onload是内置的 JavaScript 事件,但由于它的实现在浏览器(Firefox、Internet Explorer 6、Internet Explorer 8 和Opera)之间有微妙的怪癖,jQuery 提供了,它将这些抽象出来,并在页面的 DOM 准备好后立即触发(不等待图像等)。document.ready
$(document).ready(note that it's notdocument.ready, which is undefined) is a jQuery function, wrapping and providing consistencyto the following events:
$(document).ready(请注意,它不是document.ready,这是未定义的)是一个 jQuery 函数,用于包装以下事件并提供一致性:
document.ondomcontentready/document.ondomcontentloaded- a newish event which fires when the document's DOM is loaded (which may be some time beforethe images, etc. are loaded); again, slightly different in Internet Explorer and in rest of the world- and
window.onload(which is implemented even in old browsers), which fires when the entire page loads (images, styles, etc.)
document.ondomcontentready/document.ondomcontentloaded- 加载文档的 DOM 时触发的新事件(可能在加载图像等之前的一段时间);再次,在 Internet Explorer 和世界其他地方略有不同- 和
window.onload(即使在旧浏览器中也实现),当整个页面加载(图像、样式等)时触发
回答by James Drinkard
$(document).ready()is a jQuery event. JQuery's $(document).ready()method gets called as soon as the DOM is ready (which means that the browser has parsed the HTML and built the DOM tree). This allows you to run code as soon as the document is ready to be manipulated.
$(document).ready()是一个 jQuery 事件。$(document).ready()一旦 DOM 准备好(这意味着浏览器已经解析了 HTML 并构建了 DOM 树),JQuery 的方法就会被调用。这使您可以在文档准备好进行操作时立即运行代码。
For example, if a browser supports the DOMContentLoaded event (as many non-IE browsers do), then it will fire on that event. (Note that the DOMContentLoaded event was only added to IE in IE9+.)
例如,如果浏览器支持 DOMContentLoaded 事件(许多非 IE 浏览器都支持),那么它将在该事件上触发。(注意 DOMContentLoaded 事件仅在 IE9+ 中添加到 IE 中。)
Two syntaxes can be used for this:
为此可以使用两种语法:
$( document ).ready(function() {
console.log( "ready!" );
});
Or the shorthand version:
或者简写版本:
$(function() {
console.log( "ready!" );
});
Main points for $(document).ready():
要点$(document).ready():
- It will not wait for the images to be loaded.
- Used to execute JavaScript when the DOM is completely loaded. Put event handlers here.
- Can be used multiple times.
- Replace
$withjQuerywhen you receive "$ is not defined." - Not used if you want to manipulate images. Use
$(window).load()instead.
- 它不会等待图像加载。
- 用于在 DOM 完全加载时执行 JavaScript。将事件处理程序放在这里。
- 可以多次使用。
- 更换
$用jQuery,当你收到“$没有定义”。 - 如果要操作图像,则不使用。使用
$(window).load()来代替。
window.onload()is a native JavaScript function. The window.onload()event fires when all the content on your page has loaded, including the DOM (document object model), banner ads and images. Another difference between the two is that, while we can have more than one $(document).ready()function, we can only have one onloadfunction.
window.onload()是一个原生的 JavaScript 函数。window.onload()当页面上的所有内容都已加载时,该事件将触发,包括 DOM(文档对象模型)、横幅广告和图像。两者之间的另一个区别是,虽然我们可以拥有多个$(document).ready()功能,但我们只能拥有一个onload功能。
回答by Vivek
A Windows loadevent fires when all the content on your page is fully loaded including the DOM (document object model) content and asynchronous JavaScript, frames and images. You can also use body onload=. Both are the same; window.onload = function(){}and <body onload="func();">are different ways of using the same event.
一个Windows负载事件触发时,所有的页面上的内容满载包括DOM(文档对象模型)的内容和异步的JavaScript,框架和图像。您也可以使用 body onload=。两者都是一样的;window.onload = function(){}并且<body onload="func();">是使用相同事件的不同方式。
jQuery $document.readyfunction event executes a bit earlier than window.onloadand is called once the DOM(Document object model) is loaded on your page. It will not wait for the images, frames to get fully load.
jQuery$document.ready函数事件执行时间早于window.onloadDOM(文档对象模型)加载到页面上后调用。它不会等待图像、帧完全加载。
Taken from the following article:
how $document.ready()is different from window.onload()
摘自以下文章:
how $document.ready()is different fromwindow.onload()
回答by dev4092
$(document).ready(function() {
// Executes when the HTML document is loaded and the DOM is ready
alert("Document is ready");
});
// .load() method deprecated from jQuery 1.8 onward
$(window).on("load", function() {
// Executes when complete page is fully loaded, including
// all frames, objects and images
alert("Window is loaded");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
回答by deck
A word of caution on using $(document).ready()with Internet Explorer. If an HTTP request is interrupted beforethe entire document is loaded (for example, while a page is streaming to the browser, another link is clicked) IE will trigger the $(document).readyevent.
$(document).ready()与 Internet Explorer一起使用时的注意事项。如果在加载整个文档之前HTTP 请求被中断(例如,当页面流式传输到浏览器时,单击了另一个链接)IE 将触发该$(document).ready事件。
If any code within the $(document).ready()event references DOM objects, the potential exists for those objects to be not found, and Javascript errors can occur. Either guard your references to those objects, or defer code which references those objects to the window.load event.
如果$(document).ready()事件中的任何代码引用 DOM 对象,则存在找不到这些对象的可能性,并且可能发生 Javascript 错误。要么保护您对这些对象的引用,要么将引用这些对象的代码推迟到 window.load 事件。
I have not been able to reproduce this problem in other browsers (specifically, Chrome and Firefox)
我无法在其他浏览器(特别是 Chrome 和 Firefox)中重现此问题
回答by Илья Зеленько
A little tip:
一个小技巧:
Alwaysuse the window.addEventListenerto add an event to window. Because that way you can execute the code in different event handlers .
始终使用window.addEventListener向窗口添加事件。因为这样您就可以在不同的事件处理程序中执行代码。
Correct code:
正确代码:
window.addEventListener('load', function () {
alert('Hello!')
})
window.addEventListener('load', function () {
alert('Bye!')
})
Invalid code:
无效的代码:
window.onload = function () {
alert('Hello!') // it will not work!!!
}
window.onload = function () {
alert('Bye!')
}
This is because onload is just property of the object, which is overwritten.
这是因为 onload 只是对象的属性,它被覆盖了。
By analogy with addEventListener, it is better to use $(document).ready()rather than onload.
与 类比addEventListener,使用$(document).ready()比 onload更好。
回答by abstraktor
Events
活动
$(document).on('ready', handler)binds to the ready event from jQuery. The handler is called when the DOM is loaded. Assets like images maybe still are missing. It will never be called if the document is ready at the time of binding. jQuery uses the DOMContentLoaded-Event for that, emulating it if not available.
$(document).on('ready', handler)从 jQuery 绑定到 ready 事件。加载 DOM 时调用处理程序。像图像这样的资产可能仍然缺失。如果文档在绑定时准备好,它将永远不会被调用。jQuery为此使用DOMContentLoaded-Event,如果不可用则模拟它。
$(document).on('load', handler)is an event that will be fired once all resources are loadedfrom the server. Images are loaded now. While onloadis a raw HTML event, readyis built by jQuery.
$(document).on('load', handler)是从服务器加载所有资源后将触发的事件。现在加载图像。虽然onload事件是原始的HTML事件,准备由jQuery的建立。
Functions
职能
$(document).ready(handler)actually is a promise. The handler will be called immediately if document is ready at the time of calling.Otherwise it binds to the ready-Event.
$(document).ready(handler)其实是一个承诺。如果在调用时文档已准备好,将立即调用处理程序。否则它绑定到ready-Event。
Before jQuery 1.8, $(document).load(handler)existed as an alias to $(document).on('load',handler).
在 jQuery 1.8 之前,$(document).load(handler)作为$(document).on('load',handler).
Further Reading
进一步阅读
回答by Alireza
The $(document).ready()is a jQueryevent which occurs when the HTML document has been fully loaded, while the window.onloadevent occurs later, when everything including images on the page loaded.
这$(document).ready()是一个jQuery事件,当 HTML 文档完全加载时window.onload发生,而该事件稍后发生,当包括页面上的图像在内的所有内容加载时。
Also window.onload is a pure javascript event in the DOM, while the $(document).ready()event is a method in jQuery.
另外 window.onload 是 DOM 中的纯 javascript 事件,而该$(document).ready()事件是 jQuery 中的方法。
$(document).ready()is usually the wrapper for jQuery to make sure the elements all loaded in to be used in jQuery...
$(document).ready()通常是 jQuery 的包装器,以确保所有加载的元素都可以在 jQuery 中使用...
Look at to jQuery source code to understand how it's working:
查看 jQuery 源代码以了解它是如何工作的:
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
Also I have created the image below as a quick references for both:
我还创建了下面的图像作为两者的快速参考:
回答by Amir Mehdi Delta
window.onload:A normal JavaScript event.
window.onload:一个普通的 JavaScript 事件。
document.ready:A specific jQuery event when the entire HTML has been loaded.
document.ready:加载整个 HTML 时的特定 jQuery 事件。


