Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第53天 document的load 和ready有什么区别? #209

Open
haizhilin2013 opened this issue Jun 7, 2019 · 7 comments
Open

[js] 第53天 document的load 和ready有什么区别? #209

haizhilin2013 opened this issue Jun 7, 2019 · 7 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第53天 document的load 和ready有什么区别?

@haizhilin2013 haizhilin2013 added the js JavaScript label Jun 7, 2019
@Amour1688
Copy link

window.onload

  • 在页面资源(比如图片和媒体资源,它们的加载速度远慢于DOM的加载速度)加载完成之后才执行

document.onload

  • DOM加载完执行

@myprelude
Copy link

主要执行顺序的区别,load:页面资源加载完成; ready:是dom加载完成。

一般我们都在js脚本都写在onload 保证dom节点都能获取。但是有时只需要dom节点加载完成就执行代码,提前执行js脚本就可放到ready里面 jQuery也为此提供了onReady方法

@kruzabc
Copy link

kruzabc commented Jan 2, 2020

并没有 document.onload的写法。

只有如下的写法:

document.addEventListener('DOMContentLoaded',function () {
        alert(1)
});

window.onload = function () {
        alert(2)
}

分别是dom加载完成, 和 页面资源加载完成(当阻塞资源与非阻塞资源全部加载完才会触发)

显然 window.onload 是比较DOMContentLoaded 要晚触发的。

@xuxihua
Copy link

xuxihua commented Jan 15, 2020

document ready
语法

$(document).ready(function(){})
// 或者简写
$(function(){})

document load == window.onload
语法

$(document).load(function(){})
// 原生js
window.onload = function() {}

dom文档执行顺序:

  1. 解析HTML结构
  2. 加载外部脚本和样式表文件
  3. 解析并执行脚本代码
  4. 构建html dom模型 // ready
  5. 加载图片等外部文件
  6. 页面加载完毕 // load

@laboonly
Copy link

在所有资源完成加载时调用load,包括图像。在DOM准备好进行交互时被触发ready。

从MDN中,window.onload:

加载事件在文档加载过程结束时触发。此时,文档中的所有对象都在DOM中,并且所有图像和子帧都已完成加载。

从jQuery API文档中.ready(处理程序):

尽管JavaScript在呈现页面时提供了用于执行代码的加载事件,但直到所有资产(如图像)都已完全收到后才会触发此事件。在大多数情况下,脚本可以在DOM层次结构完全构建后立即运行。传递给.ready()的处理程序保证在DOM准备就绪后执行,因此这通常是附加所有其他事件处理程序并运行其他jQuery代码的最佳位置。在使用依赖CSS样式属性值的脚本时,在引用脚本之前引用外部样式表或嵌入样式元素很重要。

@MrZ2019
Copy link

MrZ2019 commented Nov 20, 2020

主要执行顺序的区别,load:页面资源加载完成; ready:是dom加载完成。

一般我们都在js脚本都写在onload 保证dom节点都能获取。但是有时只需要dom节点加载完成就执行代码,提前执行js脚本就可放到ready里面 jQuery也为此提供了onReady方法

@xiaoqiangz
Copy link

onready 是 dom加载完成时触发
onload 是页面所有元素加载完成时触发
onload在onready之后

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

8 participants