Difference between $(window).load() and $(document

2018-12-31 15:46发布

What is the difference between $(window).load(function() {}) and $(document).ready(function() {}) in jQuery?

标签: jquery
12条回答
其实,你不懂
2楼-- · 2018-12-31 15:54

I think $(window).load event is not supported for 3.x jquery..

查看更多
谁念西风独自凉
3楼-- · 2018-12-31 15:57
$(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready
 alert("document is ready");
});


$(window).load(function() {
 // executes when complete page is fully loaded, including all frames, objects and images
 alert("window is loaded");
});
查看更多
荒废的爱情
4楼-- · 2018-12-31 16:02
  • document.ready is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all content.
  • window.onload fires later (or at the same time in the worst/failing cases) when images and such are loaded, so if you're using image dimensions for example, you often want to use this instead.
查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 16:03

document.ready (jQuery) document.ready will execute right after the HTML document is loaded property, and the DOM is ready.

DOM: The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents.

$(document).ready(function()
{
   // executes when HTML-Document is loaded and DOM is ready
   alert("(document).ready was called - document is ready!");
});

window.load (Built-in JavaScript) The window.load however will wait for the page to be fully loaded, this includes inner frames, images etc. * window.load is a built-in JavaScript method, it is known to have some quirks in old browsers (IE6, IE8, old FF and Opera versions) but will generally work in all of them.

window.load can be used in the body's onload event like this (but I would strongly suggest you avoid mixing code like this in the HTML, as it is a source for confusion later on):

$(window).load(function() 
{
   // executes when complete page is fully loaded, including all frames, objects and images
   alert("(window).load was called - window is loaded!");
});
查看更多
看淡一切
6楼-- · 2018-12-31 16:06

$(document).ready happens when all the elements are present in the DOM, but not necessarily all content.

$(document).ready(function() {
    alert("document is ready");
});

window.onload or $(window).load() happens after all the content resources (images, etc) have been loaded.

$(window).load(function() {
    alert("window is loaded");
});
查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 16:06

Notably this function was deprecated in 1.8, and removed in jquery 3.0

More info here: Object doesn't support property or method 'indexOf'

查看更多
登录 后发表回答