jQuery multiple document ready queue order

前端 未结 4 1021
忘掉有多难
忘掉有多难 2021-01-05 03:33

I know calls to $(function(){ }) in jQuery are executed in the order that they are defined, but I\'m wondering if you can control the order of the queue?

For example

4条回答
  •  情歌与酒
    2021-01-05 04:02

    You can use jQuery promise to achieve something like this.

    Following is an example where jQuery.ready.promise helps managing the order of execution of DOM Ready Blocks:

    1. In the following example, the first DOM Ready block is trying to access the height of the test div which is appended to the body in a later DOM Ready block. As in the Fiddle it fails to get it.

      jQuery(function () {
          var testDivHeight = jQuery("#test-div").outerHeight();
          if(testDivHeight) {
              alert("Height of test div is: "+testDivHeight);
          } else {
              alert("Sorry I cannot get the height of test div!");
          }
      });
      jQuery(function () {
          jQuery('body').append('
      '); });

      Fiddle: http://jsfiddle.net/geektantra/qSHec/

    2. In the following example, it is doing exactly the same as the example before using jQuery.ready.promise. As in the Fiddle it works as required.

      jQuery(function () {
          jQuery.ready.promise().done(function () {
              var testDivHeight = jQuery("#test-div").outerHeight();
              if(testDivHeight) {
                  alert("Height of test div is: "+testDivHeight);
              } else {
                  alert("Sorry I cannot get the height of test div!");
              }
          });
      });
      jQuery(function () {
          jQuery('body').append('
      '); });

      Fiddle: http://jsfiddle.net/geektantra/48bRT/

提交回复
热议问题