Is $(document).ready() called after loading all script files in the body? [duplicate]
Asked Answered
F

3

8

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

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 :

<!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() ?

Franciskus answered 7/6, 2013 at 12:8 Comment(1)
$({ hello(); }) is syntax errorDestruction
A
4

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>
Allhallowmas answered 7/6, 2013 at 12:12 Comment(4)
But it is called after loading all images too, Do you think it is a good idea to use load !!!Franciskus
The good idea would be to call hello() function inside helloFuncDeclaration.js file after declaration or use the onload event of this script tagAllhallowmas
helloFuncDeclaration.js maybe some remote library and I want to calling the function or declaring some objects in my own code block...Franciskus
I have used $(document).ready() for my own custom jquery code. And for all advertisement scripts (like Google AdSense or other providers) I activated them using $(window).load(), which works well!Arjuna
S
2

To be sure , you can use 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.

Shotgun answered 7/6, 2013 at 12:12 Comment(0)
C
1

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

Clarance answered 7/6, 2013 at 12:11 Comment(5)
it runs after DOM is ready, so noAllhallowmas
I don't understand why this answer was down voted. #2398034 and #6195757 clearly state that script inside the body will always be loaded before the ready event fires.Laud
No, it's called after DOM elements are downloaded not all assets.Intracutaneous
That means scripts inside the body tag. Optimally you do not have scripts inside the body tag.Siriasis
this answer is wrong and it could lead to bugs in JS. document.ready event do not means, that all JS from body was loaded.Doak

© 2022 - 2024 — McMap. All rights reserved.