Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are javascript functions executed

Tags:

javascript

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?

like image 722
Victor Avatar asked Oct 03 '09 15:10

Victor


People also ask

Do functions execute as soon as they are read by the browser?

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.

Where JavaScript code is executed?

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”.


2 Answers

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).

like image 136
x0n Avatar answered Sep 23 '22 10:09

x0n


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.)

like image 29
cuisdy Avatar answered Sep 22 '22 10:09

cuisdy