简体   繁体   中英

JQuery .load callback is called before .ready callback in loaded script, what is proper way of initialization loaded scripts?

In main document on button click I am loading content of some div with

$("#my_div").load(function() {
    alert("Loaded");
});

The loaded content is just script

<script>
alert("Init outside");
$(document).ready(function() {
    alert("Init inside");
}
</script>

And sequence of alerts is "Init outside", "Loaded", "Init inside".

Am I correct, that it is proper way to initialize loaded script in script body, means where alert("Init outside") resides? Not in .ready() handler?

Because in my real workflow I am definitely need to initialize script before .load() callback is processed. In .load() callback I am showing loaded modal, but before, the modal should initialize itself, ie set on('show.bs.modal') handler etc.

It's quite strange, that initialization should happen outside $(document).ready() handler if I need such sequence, so that's why I am asking.

UPD: The question is not a duplicate, cause it's related more on JQuery-defined sequence of initialization and callbacks.

It depends somewhat on what you're doing in the modal-initialising step, but if there's no asynchronous element to it you shouldn't need to put the initialising code & the code that actually shows it in separate callbacks. If the code blocks are in callbacks for different events, there's ambiguity around which one will run first - you want to know for sure they'll run in order.

For example:

$(document).ready(function() {
  $('#modal').on('show.bs.modal', function() {
    // your init code
  });

  $('#modal').modal('show');
}

Binding a callback to the show.bs.modal event as you've described is a synchronous action, so the code can be placed in the same block. .ready() just waits for elements to be ready (which is all you should need), while .load() waits for all content to be loaded, but either will ensure your elements have loaded before their callbacks execute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM