简体   繁体   English

我是否必须使用为 jQuery 准备的文件?

[英]Do I have to use document ready for jQuery?

I have a script that I want to use, however, I don't know if I require to put document ready.我有一个我想使用的脚本,但是,我不知道我是否需要准备好文档。

 $(window).scroll(function(){ $(".hero-h1").css("opacity", 1 - $(window).scrollTop() / 250); });

If position and run your script so that the elements it depends on already exist at the time it runs, no.如果 position 并运行您的脚本,以便它所依赖的元素在运行时已经存在,则不。

This is essentially the same question as whether someone needs to use这与是否有人需要使用本质上是相同的问题

window.addEventListener('DOMContentLoaded', () => {
  // all of the code
});

If, at the time your script runs, you try to select an element that isn't always present regardless - like a particular <div> on the page - for example如果,在您的脚本运行时,您尝试 select 一个无论如何并不总是存在的元素 - 例如页面上的特定<div>

$('.mybutton').on('click', () => {
  // ...

Then at the time that the above line runs, you need to make sure that .mybutton exists on the page.然后在上面的行运行时,您需要确保页面上存在.mybutton

This can be accomplished in a few ways.这可以通过几种方式来实现。 One of these ways is by wrapping the whole script in .ready (or, as is usually preferred nowadays, just a plain function):其中一种方法是将整个脚本包装在.ready中(或者,现在通常首选,只是一个普通函数):

$(() => {
  $('.mybutton').on('click', () => {
    // ...

Another way it can be accomplished is by putting your script after all the elements that it depends on in the HTML markup - for example可以完成的另一种方法是将脚本放在 HTML 标记中依赖的所有元素之后 - 例如

// lots of HTML code
<button class="mybutton">click</button>
<script src="myscript.js"><script>
</body>

If you put your script at the end of the body, all elements from the static page markup will exist in the DOM by then.如果将脚本放在正文的末尾,那么 static 页面标记中的所有元素都将存在于 DOM 中。

A third way is to give your script the defer attribute.第三种方法是为您的脚本赋予defer属性。

<script defer src="myscript.js"><script>

This will ensure that all static elements are loaded before the script runs.这将确保在脚本运行之前加载所有 static 元素。

For this particular case of yours, if all you do is add a scroll handler to the window, then there aren't any elements to wait for in order to attach the handler, so you may not need to use any of the approaches above.对于您的这种特殊情况,如果您所做的只是将滚动处理程序添加到 window,则无需等待任何元素来附加处理程序,因此您可能不需要使用上述任何方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM