[英]Why does normal javascript do not need $(document).ready like jQuery?
I'm currently learning jQuery after finishing JavaScript course. 在完成JavaScript课程之后,我目前正在学习jQuery。 The document says that the
ready
method waits until DOM finished loading. 该文档说
ready
方法要等到DOM完成加载。 However, I have 2 points I'm curious about. 但是,我有2分让我很好奇。 1) Since the script tag are usually added at the end of the body tag, shouldn't the DOM already finished loading anyway without the
ready
method. 1)由于script标记通常添加在body标记的末尾,因此,如果没有
ready
方法,DOM应该不应该已经完成加载。 2) If we need the ready
method in jQuery, why do we not need it when writing usual JavaScript too? 2)如果我们需要jQuery中的
ready
方法,为什么在编写常规JavaScript时也不需要它?
1) Since the script tag are usually added at the end of the body tag, shouldn't the DOM already finished loading anyway without the ready method. 1)由于script标记通常添加在body标记的末尾,因此,如果没有ready方法,DOM应该不应该已经完成加载。
Yes you are right, if script tag is added add the end of the body, you do not need to wrap your code with $(document).ready()
as the DOM elements are already available to use in the code. 是的,您是对的,如果在正文的末尾添加了脚本标记,则无需使用
$(document).ready()
来包装代码,因为DOM元素已可以在代码中使用。
2) If we need the ready method in jQuery, why do we not need it when writing usual JavaScript too? 2)如果我们需要jQuery中的ready方法,为什么在编写常规JavaScript时也不需要它?
The jQuery equivalent of $(document).ready()
is DOMContentLoaded
相当于
$(document).ready()
的jQuery是DOMContentLoaded
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
当初始HTML文档已完全加载并解析,而无需等待样式表,图像和子帧完成加载时,将触发DOMContentLoaded事件。
Please Note: You can also use script defer
attribute 请注意:您也可以使用脚本
defer
属性
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
设置此布尔值属性是为了向浏览器指示脚本应在解析文档之后但在触发DOMContentLoaded之前执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.