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
3 Answers
Reset to default 3The 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
版权声明:本文标题:Importing javascript file multiple times on same page - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744968938a2635116.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论