简体   繁体   中英

in my javascript file, which executes first, initialization code or code in an $(document).ready() event

A project I am working on has some initialization code (not in any function) and some code in a jQuery $(document).ready() event. Which code executes first? Why? I'd also like to know why it might have been written that way? Thanks. For example:

'use strict';
let inputs = [];
function func(){};
function func2(){};
$(document).ready(function(){
  const a = 1;
  func2();
})

The code will execute from the top down: 'use strict'; executes first, followed by let inputs = []; , etc.

Note that executing your function definitions function func(){}; and function func2(){}; don't actually call the functions at that point.

Once the document has loaded, it calls the anonymous function passed to $(document).ready() which executes const a = 1; and finally calls func2(); .

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ).ready() method will run once the page DOM is ready to execute JavaScript code.

In this code fun2() will call first after the document is loaded.

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