在DOM准备就绪之前运行jQuery代码? [英] Running jQuery code before the DOM is ready?

查看:113
本文介绍了在DOM准备就绪之前运行jQuery代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在DOM准备就绪之前执行jQuery代码?

Is there a way to execute jQuery code before the DOM is ready ?

推荐答案

jQuery只是Javascript,因此问题实际上是在DOM准备就绪之前是否可以运行JavaScript",我猜这是您的意思.文档而不是DOM.

jQuery is just Javascript, so the question is really "Is it possible to run JavaScript before the DOM is ready" and with that I'm guessing you mean the document and not DOM.

如果我们可以同意,问题是在文档准备好之前是否可以运行JavaScript".那么答案是肯定的.遇到问题时将执行JavaScript.

If we can agree that the question is "Is it possible to run JavaScript before the document is ready". Then the answer is yes. The JavaScript will be executed when encountered.

这就是为什么您几乎总是看到$(function(){...})$(document).ready(function(){...})的原因,因为大多数jQuery代码都要求文档准备就绪,但是肯定会在文档准备就绪之前执行附加事件处理程序的代码(否则它将无法执行)处理文档准备事件).

That's why you almost always see either $(function(){...})or $(document).ready(function(){...}) because most jQuery code requires the document to be ready but the code attaching the event handler is certainly executed before the document is ready (otherwise it wouldn't be able to handle the document ready event).

通常,您应该将包含Javascript的内容放在HTML的底部,但如果要使其更早执行,则可以将其更早地放置在文档中,例如在标题中.

Usually you should place your Javascript includes at the bottom of your HTML but if you want it executed earlier you can simply place it earlier in the document e.g. in the header.

<html>
  <head>
     ...
     <script>
        //place your code to be executed early here
     </script>
  </head>
...
</html>

这篇关于在DOM准备就绪之前运行jQuery代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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