tags:

views:

145

answers:

3

I have a javascript file called pendingAjaxCallsCounter.js with a variable "var pendingAjaxCalls" which is incremented/decremented when various methods in the js file are called.

Separately, I have created an automated testing app which checks that the pendingAjaxCalls has a value of 0 before interacting with any page. I'm wondering, if a given page, were to import the js file multiple times; multiple statements, how would that affect the value of my variable "var pendingAjaxCalls"?

A: 

Each time you include a script using a script tag, the browser will download the file and evaluate it. Each time you include a JavaScript file the contents will be evaluated.

Fabian Jakobs
+1  A: 

The script would be run each time it was included, but make sure that you don't redefine the pendingAjaxCalls variable each time. i.e. Check it's defined before declaring it with something like:

if(!pendingAjaxCalls)
  var pendingAjaxCalls=0;

/* code happens here */

pendingAjaxCalls++;
Karl B
This lead me to my solution. Thanks.I ended up with a statement like this:if(pendingAjaxCalls == null){ var pendingAjaxCalls = 0;}/* .... *//* code that incremenets/decrements pendingAjaxCalls */Based on what I read in a javascript book, this if statement will test if the variable pendingAjaxCalls is undefined or null based on javascript type coercion that happens in the "==". This way if the variable has already been "spit out" somewhere else in the code I won't end up messing with it.
Alex
Yes - and if(!pendingAjaxCalls) is equivalent to if(pendingAjaxCalls == null), since 0 == null == false. But I'm glad it helped!
Karl B
A: 

If the actual call to the function that increments your variable is being inserted more than once, you could be incrememting it multiple times.

On the other hand, if only the function that increments it is being inserted multiple times (not the function call), then JavaScript will use the most recently defined version of this function. So it shouldn't be incremented extra times in that case.

In other words, if you insert the same function twice but only call it once, you don't have to worry about "both copies" of the function being called, since one copy effectively overwrites the other.

Tim Goodman