Do my functions have to be defined in jQuery's .ready() method?


Do my functions have to be defined in jQuery’s .ready() method?


No, they don’t. When using jQuery we can define the functions we want to use after our document is loaded, inside of jQuery’s .ready() method. This way of defining functions ensures that our functions are scoped to the .ready() method and will not be available for access from outside of .ready(). If we define our functions outside of .ready() said functions will be available for use both inside and outside of .ready().

Defining a function inside .ready():

$(document).ready(() => {
  function sayHello (){ //defines sayHello inside the .ready() method

sayHello(); //this will error as sayHello is not available outside of the .ready() method

Defining a function outside of .ready():

function sayHello () { //defines sayHello outside of the .ready() method

$(document).ready(() => {
  sayHello(); //sayHello is available inside .ready()

If we’re placing everything within the ready tag, why do we still have to place the script at the end of the body and not in the head?


I understand your idea.
The script will not execute until the document is loaded, thats right.

But in this case, it’s about the loading order and not the timing of execution.
When you load a website, you want to see the website first and then use the different functionalities.
Not the other way around!

The browser read files from top to bottom.
So the head will be loaded first and then the body.
When you put the script in the head, the browser will load the script first and then the content of the website.

The first disadvantage is, that you have to wait a bit longer until you can see the content of the website.
The second disadvantage is, that your script can potentially run into errors, because at this moment the content of the website is not rendered and your script could claim many reference errors, because the content to manipulate doesn’t “exists”.

So it’s best practice to put the script still in the head, but with the “defer” attribute.
The “defer” attribute tells the browser to load this script only when the document is loaded.

In older HTML files, it’s more common to put the script at the end of the body.
Both ways are fine.

For the examples above, do we have to put the function sayHello() before .ready()? or the order doesn’t matter?