0

I have this very simple html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
  </head>
  <body>

    <script src="https://code.jquery.com/jquery.js"></script>

    <script src="js/app.js"></script>
    <script src="js/model/dinnerModel.js"></script>
    <script src="js/view/exampleView.js"></script>
  </body>
</html>

And the javascript files that are included in the bottom are:

app.js:

$(function() {
    var model = new DinnerModel();

    var exampleView = new ExampleView($("#exampleView"));

});

dinnermodel.js:

var DinnerModel = function(){
    // some js stuff
}

exampleView.js:

var ExampleView = function () {
     // more js stuff
}

This runs fine for me, and my question is: why? When app.js is included in its script tag, dinnermodel.js and exampleView.js have clearly not been loaded yet, so I should get an error in app.js saying that DinnerModel is not declared, right?

Sahand
  • 7,980
  • 23
  • 69
  • 137
  • Possible duplicate of [How does jQuery's "document ready" function work?](https://stackoverflow.com/questions/5959194/how-does-jquerys-document-ready-function-work) – Patrick Roberts Jan 26 '18 at 16:38
  • What did you think `$(function () { ..` does? – JJJ Jan 26 '18 at 16:38
  • @PatrickRoberts That doesn't answer this. That question is about how `document.ready` works internally, but not the implications on other scripts. – Barmar Jan 26 '18 at 17:28

2 Answers2

3

Because $(function() {}) waits until dom is ready and that means the other scripts have loaded before the code inside it gets executed

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

Great question.

It works because you're waiting for the document to be ready, please refer to this website. https://learn.jquery.com/using-jquery-core/document-ready/

Doing $( document ).ready(function() { or $(function() { is the exact same thing.

By the time the page executes the function inside $() the whole content was loaded and ready to use.

Joao Lopes
  • 936
  • 5
  • 9