Skip to content
Advertisement

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);
  });

Advertisement

Answer

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.

Advertisement