[英]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.我正在处理的项目有一些初始化代码(不在任何函数中)和 jQuery $(document).ready() 事件中的一些代码。 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';
代码将自上而下执行:
'use strict';
executes first, followed by let inputs = [];
首先执行,然后是
let inputs = [];
, etc. , ETC。
Note that executing your function definitions function func(){};
请注意,执行您的 function 定义
function func(){};
and function func2(){};
和
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;
加载文档后,它调用匿名 function 传递给
$(document).ready()
执行const a = 1;
and finally calls func2();
最后调用
func2();
. .
The ready() method is used to make a function available after the document is loaded. ready()方法用于在加载文档后使 function 可用。 Whatever code you write inside the $(document ).ready() method will run once the page DOM is ready to execute JavaScript code.
一旦页面 DOM 准备好执行 JavaScript 代码,您在$(document).ready()方法中编写的任何代码都将运行。
In this code fun2() will call first after the document is loaded.
在此代码中,fun2() 将在文档加载后首先调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.