Multiple $ (document) .ready and $ (window) .load in $ (document) .ready

I have 2 questions. First of all, this is not my job. I am currently looking at other JavaScript files. I can’t give the exact code, but I can show what interests me.

I see a lot in JavaScript files $(document).ready(function(){});. I know what it does $(document).ready, the callback function will be called when the DOM tree is loaded. Is there a reason someone would use more than one callback $(document).ready? I do not understand.

In addition, another thing I saw was $(window).loadinside $(document).ready, for example:

$(document).ready(function() {
    $(window).load(function() {
         //...
    });
});

From what I know, it $(window).load()is called when the entire content of the page is loaded, for example, assets and images, etc. I would think that $(window).load()- this is the last thing that is called after $(document).ready. Is there a time when $(window).loadBEFORE is called $(document).ready, and is there a reason why you would put $(window).loadinside a $(document).ready?

+4
source share
2 answers

Yes, jQuery provides an event to be readyraised before load. Even in IE8- (where it is DOMContentLoadednot supported), it works this way. But let's look at the following code:

<!doctype html>

<title>Ready vs load test</title>

<style>body {white-space: pre}</style>

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

<script>
  ~function () {
    function log(msg) {
      document.body.innerHTML += msg + "\n";
    }

    function handler(msg) {
      return function () {
        log(msg);
      }
    }

    $(window).load(handler("5. load #1"));
    $(document).ready(handler("1. ready #2"));
    $(window).load(handler("6. load #3"));
    $(document).ready(handler("2. ready #4"));
    $(document).ready(function () {
      log("3. ready #5");
      $(window).load(handler("8. load #6"));
    });
    $(document).ready(handler("4. ready #7"));
    $(window).load(handler("7. load #8"));
  }();
</script>

Result

1. ready #2
2. ready #4
3. ready #5
4. ready #7
5. load #1
6. load #3
7. load #8
8. load #6

7 8. load, ready, . , , , ( ) load .

$(window).load $(document).ready , ?

script. , :

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
  $(document).ready(function () {
    $(window).load(function () {
      $.magic.value = 12;
    });
  });
</script>

<script>
  $(window).load(function () {
    $.magic = {};
  });
</script>
Hide result

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
  $(document).ready(function () {
  });

  $(window).load(function () {
    $.magic.value = 12;
  });
</script>

<script>
  $(window).load(function () {
    $.magic = {};
  });
</script>
Hide result
+3

$(document).ready , DOM , , $(window).load, . img-ele, - - .

, , .

0

Source: https://habr.com/ru/post/1670275/


All Articles