Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
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);
  });

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If position and run your script so that the elements it depends on already exist at the time it runs, no.

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

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

Then at the time that the above line runs, you need to make sure that .mybutton exists on the page.

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

$(() => {
  $('.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

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

A third way is to give your script the defer attribute.

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

This will ensure that all static elements are loaded before the script runs.

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda