Short jQuery question!

@Paul_Wilkins gave me a code this week starting with:

$(document).ready(function domReady() {

Sometimes I see code starting with just:

$(function () {

Can someone explain to me what the difference is? Excuse me for my ignorance but my js/jquery skills ar e not that good.

Thank you in advance

Hi Donboe, one is just a shortcut for the other. That is to say they are equivalent.

Personally, I prefer the the second, $(function() {});. Or better still, put your JavaScript before the closing body tag and do away with the check altogether.

The jQuery code waits for the DOM to be loaded before running the function.

With vanilla JavaScript we achieve the same thing by placing our scripts at the end of the body, just before the </body> tag.

That is also jQuery code that does the same thing. It’s a shortcut for the first code.

The following page shows several different ways that jQuery lets do the same thing, of waiting for the document to be ready before running the JavaScript.

@James_Hibbard and @Paul_Wilkins. Thank you both for the clear explanation. Very helpfull :+1:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.