开发者

Importing javascript file multiple times on same page

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 pendi开发者_如何学编程ngAjaxCalls"?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜