I think it has to be an easy question but I have been searching around and have not found the answer anywhere.
The think is that I have an html page with some scripts (in the body) like this one:
<script type="text/javascript">grf();</script>
The grf() function is defined in an external .js file. The question is: is this function executed once the browser has loaded the page AND all of its external js files? Or it can be the case that the function is executed before the .js files are loaded? And if so, how can I prevent this?
Browser executes it when it sees the tag. Not only other scripts might not be loaded yet, DOM might not be constructed. However, it is guaranteed that scripts are executed in order they appear in the HTML.
Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine. The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
The function is run when it is encountered. If you want it to run after the page has loaded, the standard method is to hook the onload event of the window. jQuery has great support for this, but lets start with ground-level:
<script type="text/javascript">window.onload = function() { grf(); }</script>
This will stomp on any other onload handlers than may have been assigned previously on the page, which is why most people use jQuery which is careful to chain to previous handlers:
<script type="text/javascript">$(document).ready(function() { grf(); });</script>
Of course for this second example, you need to include the jQuery libraries further up the page (which it sounds like you're not in a position to do).
To see if a function is defined:
// functions are defined or undefined just like regular variables
function myFunc() {
/*--code here--*/
}
// So we just need to see if it's defined
if( myFunc ) {
/*--do something here--*/
} else {
/*--wait, retry or w/e--*/
}
When an external script is found, the (x)html will not be read further untill the external script is read (and code inside executed if there's any executable code there).
So, calling a function in an external file after the external file was 'included' cannot generate a function-not-defined error. (However, keep in mind that you WILL get errors if that external function tries to manipulate the DOM or elements that still "don't exist" in the page.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With