About window.onload and $(document). Ready

js Code

window.onload=function(){
   console.log(2)
}
console.log(1)

html code has nothing but:

  1. introduce the above js into the head tag
  2. body tag finally introduces
  3. introduce
  4. outside the html tag

then compare the consoles of the three cases.

  1. the first case: first 1, then 2. It is not difficult to understand that because the DOM has not been loaded in head, so wait for the document to be loaded first and output 2
  2. .
  3. the second case: my understanding is that in the final introduction, the js dom has been loaded and it should be 2 after 1. Unfortunately, my test result is still 1 after 2
  4. .
  5. third case: write script outside the entire html and tag, unfortunately 1 followed by 2

after testing the read function of jquey, the result is the same (there is no picture for typing on mobile phone)


The essence of

this problem is not DOMContentLoaded and load problems.

the subject can open devtools, to select a network

:

js

:

:

2.6s 3s :

you can clearly see that console.log was executed first.


first of all, you declare the callback function of js. When the js engine encounters a callback function during parsing, it will throw it into an event queue, and it will not be executed until other code is executed and the trigger condition occurs (here the trigger condition is window.onload).
second, window.onload occurs after all files have been loaded.


    .ready () of
  1. jQ corresponds to the DOMContentLoaded event, not load;
  2. The recommended words for .ready () are $(function () {}); or jQuery (function ($) {});
  3. script is written outside the entire html root tag? This is a non-standard way of writing.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b37183-2c06f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b37183-2c06f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?