javascript $(document).ready() 是否在加载正文中的所有脚本文件后调用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16983774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:40:33  来源:igfitidea点击:

Is $(document).ready() called after loading all script files in the body?

javascriptjquerydomdocument-readyready

提问by faressoft

Is $(document).ready() called after loading script js files in the body ?

$(document).ready() 在正文中加载脚本 js 文件后是否调用?

If I put $(document).ready() in the head in script element which take a callback function that using a functions declared in a file which its script element loaded in the body like that :

如果我将 $(document).ready() 放在脚本元素的头部,它采用一个回调函数,该函数使用在文件中声明的函数,其脚本元素加载到正文中,如下所示:

<!DOCTYPE HTML>
<html>
<script src="jquery.js" type="text/javascript"></script>
<script>
$(function(){
hello();
})
</script>
<head>
</head>
<body>

<script src="http://somewhere/helloFuncDeclaration.js" type="text/javascript"></script>

</body>
</html>

Is it a right way to do that and guarantee that the helloFuncDeclaration.js will be loaded before calling the function hello() ?

这样做并保证在调用函数 hello() 之前加载 helloFuncDeclaration.js 是一种正确的方法吗?

采纳答案by A. Wolff

To be sure, use window onload handler:

可以肯定的是,使用窗口加载处理程序:

$(window).on('load', hello);

Or use it like this:

或者像这样使用它:

<script onload="hello()" src="http://somewhere/helloFuncDeclaration.js" type="text/javascript"></script>

回答by Mohammad Adil

To be sure , you can use window.load

可以肯定的是,您可以使用 window.load

$(window).load(function(){
   hello();
})

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

当一个元素和所有子元素都被完全加载时,加载事件被发送到一个元素。此事件可以发送到与 URL 关联的任何元素:图像、脚本、框架、iframe 和 window 对象。

回答by Thelambofgoat

$(document).ready()runs after all assets were loaded, so - yes

$(document).ready()在加载所有资产后运行,所以 - 是的