在 DOM 准备好之前运行 jQuery 代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12598232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:51:22  来源:igfitidea点击:

Running jQuery code before the DOM is ready?

jquery

提问by drake035

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

有没有办法在 DOM 准备好之前执行 jQuery 代码?

回答by Rune FS

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.

jQuery 只是 Javascript,所以问题实际上是“在 DOM 准备好之前是否可以运行 JavaScript”,我猜你指的是文档而不是 DOM。

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.

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

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).

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

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.

通常你应该把你的 Javascript 包含在你的 HTML 的底部,但如果你希望它更早执行,你可以简单地将它放在文档的更早位置,例如在标题中。

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

回答by James Allardice

If you include jQuery in the head of your document, and then write your code in another script tag in the head, it will run before the DOM is ready:

如果您在文档的头部包含 jQuery,然后在头部的另一个脚本标记中编写代码,它将在 DOM 准备好之前运行:

<head>
    <script src="jquery.js"></script>
    <script>
        // Do some stuff before the DOM is ready
    </script>
</head>
<body>
    <!-- Browser hasn't got this far, so no elements will be available -->
</body>

However, obviously you won't be able to interact with any DOM elements, since they won't exist yet.

但是,显然您将无法与任何 DOM 元素进行交互,因为它们尚不存在。



Having said that, there isa technique you can use in modern browsers that can allow you to interact with DOM elements as they are inserted into the page (while the browser is rendering it). It relies upon CSS animation events. I've written a simple library (Progressive.js)to make this easier to handle.

说了这么多,还有就是你可以在现代浏览器,可以让它们插入到页面(在浏览器渲染它),您可以与DOM元素交互使用的技术。它依赖于CSS 动画事件。我编写了一个简单的库 (Progressive.js)以使其更易于处理。