dallin
dallin

Reputation: 9426

What is the expected behavior of a document.ready event that is added to the DOM from a JQuery.load ajax call?

I have a website that is loading multiple JQueryUI dialog windows at once. I get the HTML for each of these dialog windows using a JQuery.load ajax call. The content of these dialogs might also be loaded as an individual webpage at times, so each of them has their own $(document).ready() function (or a $(function(){}) for shorthand). I'm not sure how a $(document).ready() function is supposed to behave when loaded by ajax after the original document is fully loaded.

I've run into some weird functionality here. For some reason, it's running the code within the document.ready event the moment it reaches the declaration, as if it were sequential code rather than an event assignment. For example:

<script>    
    console.log(1);

    $(function () {
        console.log(3);
    }

    console.log(2)
</script>

I would think that it would wait to execute until after the global level script finished due to the single thread nature of JS and event bubbling. In other words, I would expect this to be the output:

1
2
3

But for some reason it is actually outputting:

1
3
2

Any idea why this behavior is happening?

Upvotes: 0

Views: 163

Answers (1)

Kaiido
Kaiido

Reputation: 136707

You are dealing with a jQuery function, not with real DOM Events, and thus, you are tied to jQuery's implementation of their function.

It's quite hard to tell exactly what they are doing since this behavior did change across the evolution of the library...

But basically, there seems to be two major cases if the Events that the function should wait for has already fired:

  1. They execute the passed callback directly (apparently until jQuery 3)
  2. They execute the passed callback in a $.deferred call, i.e a Promise (since jQuery 3)

window.onload = e => {
  console.log('start of window onload');
  $(()=>console.log('$ready')); // executed synchronously
  console.log('end of window onload');
};
<!-- jQuery < 3 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

window.onload = e => {
  console.log('start of window onload');
  $(()=>console.log('$ready')); // deferred
  console.log('end of window onload');
};
<!-- jQuery >= 3 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions