admin管理员组

文章数量:1405993

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"?

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"?

Share Improve this question asked Jan 20, 2010 at 16:36 AlexAlex 7147 silver badges19 bronze badges 1
  • As of 1/28/10 I can say that all of the answers were really helpful in improving my understand of javascript, and arriving at a solution for this problem. Thanks everyone. – Alex Commented Jan 29, 2010 at 0:36
Add a ment  | 

3 Answers 3

Reset to default 3

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++;

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.

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.

本文标签: Importing javascript file multiple times on same pageStack Overflow