$(document).ready()和忽略它有什么区别? [英] What's the difference between $(document).ready() and just omit it?

查看:96
本文介绍了$(document).ready()和忽略它有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数教程中,提到了两种如何执行jquery脚本的方法:

In most tutorials, there are two ways mentioned about how to execute a jquery script:

  • 带有window.onload钩子.
  • 带有$(document).ready(function(){...})事件(可以缩写为$(function(){...}))
  • with window.onload hook.
  • with a $(document).ready(function(){...}) event (and could be abbreviated to $(function(){...}))

我发现,即使我全部忽略它们,它也可以工作,只需将代码放在<script></script>遮挡中即可达到相同的目的.就是这样:

And I found that it even works when I omit all them, just place the code in a <script></script> occlusion could achieve the same purpose. Just like this:

<html>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<body>
    <button id="btn" name="test" value="clickme">clickme</button>
</body>
<script>

//$(document).ready( function(){
//    $('#btn').on("click", function(e){
//        alert("hi")
//     }
//)})

$('#btn').on('click', function(e){
    alert('hi')
})
</script>
</html>

如您所见,未注释的代码(省略所有document.ready人员或window.onload的代码)和注释的代码都可以按预期方式给我警报.

As you can see both the un-commented code (which omit all the document.ready staff or a window.onload) and the commented code can give me a alert as expected.

所以我的问题是,在这种情况下(绑定事件),因为我可以编写更多优雅的代码作为未注释的代码段.为什么我要像大多数教程中所说的那样麻烦写代码(这就是上面的注释风格)?

So my question is, in such cases(binding events), since I can write code more elegant as the un-commented snippet. Why should I bother to write the code as in most tutorials told (which is as the commented style above) ?

推荐答案

<script>标签将按照从上至下的顺序解析HTML文档的顺序执行.这意味着将在分析文档的其余部分之前(因此在文档可用之前)执行文档顶部附近的脚本.在许多情况下,这使脚本的放置或脚本的执行时间变得重要.

<script> tags in your HTML that do not have the defer or async attributes will execute in the order the HTML document is parsed from top down. That means that a script near the top of the document will execute before the rest of the document has been parsed and thus before it is available. This makes the placement of a script or the execution timing of a script relevant in many cases.

在控制执行时间时,您至少有五个选择来执行启动脚本:

In controlling this execution timing, you have at least five choices for executing startup scripts:

  1. 您可以将脚本放在<head>部分或<body>部分的顶部,并在加载时执行该脚本.这样做的缺点是尚未加载DOM,因此您无法对页面中的元素进行操作.

  1. You can put the script in the <head> section or the top of the <body> section and execute it as it loads. This has the disadvantage that the DOM is not yet loaded so you can't operate on elements within the page.

您可以在</body>标记之前插入脚本,所有DOM将被加载,并且脚本将能够访问所有内容.

You can insert the script right before the </body> tag and all of the DOM will be loaded and your script will be able to access everything.

您可以在任意位置(包括<head>标记中)插入脚本,并使用$(document).ready(fn)在DOM准备就绪之前不执行fn.在内部,jQuery监听DOMContentLoaded事件,并在触发时执行任何.ready()处理程序.

You can insert your script anywhere you want (including in the <head> tag) and use $(document).ready(fn) to not execute the fn until the DOM is ready. Internally, jQuery listens for the DOMContentLoaded event and when it fires, it executes any .ready() handlers.

您可以在任意位置(包括<head>标记中)插入脚本,并使用window.onload(fn)在DOM准备就绪并且所有外部资源(例如图像)已加载之前不执行fn.注意,您也可以使用jQuery版本$(window).load(fn).

You can insert your script anywhere you want (including in the <head> tag) and use window.onload(fn) to not execute the fn until the DOM is ready and all external resources such as images have loaded. Note, you can also use the jQuery version $(window).load(fn).

您可以在脚本标签上使用asyncdefer属性,以强制其异步加载,并稍后加载.这将产生不确定的脚本执行时间(尽管总是比仅内联的时间晚),因此您可能需要一些特定的控件,例如$(document).ready(),以在脚本执行之前知道DOM是安全的.您可以看到以下其他问题/答案脚本标记-异步&延迟加载和执行脚本顺序有关异步和延迟属性操作的更多详细信息.

You can use the async or defer attributes on the script tag to force it to load asynchronously and somewhat later. This will create an indeterminate time of script execution (though always later than if it was just inline) so you will likely need some specific control like $(document).ready() to know that the DOM is safe before your script executes. You can see these other questions/answers Script Tag - async & defer and Load and Execute order of scripts for a lot more details on the operation of the async and defer attributes.

因此,如果您小心地将脚本标签放置在正确的位置,或者启动脚本没有尝试访问DOM元素,则无需使用$(document).ready(fn)window.onload(fn).

So, if you carefully place your script tag in the right place or your startup script does not try to access DOM elements, you don't need to use either $(document).ready(fn) or window.onload(fn).

但是,如果您不能完全控制脚本的放置位置,并且需要访问DOM元素,或者希望脚本能够被放置在任何地方并且仍然可以正确执行操作,或者您只想全部<head>标签中的脚本,则需要延迟脚本的执行,直到DOM准备就绪为止,并且$(document).ready(fn)window.onload(fn)都将使其易于执行.

But, if you don't entirely control where the script is placed and you need to access DOM elements or you want your script to be able to be placed anywhere and still have it do the right thing or if you just want all your scripts in the <head> tag, then you will need to delay the execution of your script until the DOM is ready and either $(document).ready(fn) or window.onload(fn) will make it easy to do so.

这篇关于$(document).ready()和忽略它有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆