My javascript gets included multiple times with the script tag, like so:
<script src="code.js></script>
<script src="code.js></script>
<script src="code.js></script>
Right now I have this code inside code.js to make my code run only once without overwriting my namespaces:
if(typeof _ow == "undefined" ){
_ow = {};
// code in here will only run once
_ow.Auth = (function(){
})();
_ow.Template = (function(){
})();
}
Is there any better structure I could use to make my code only run once?
-
Um... why is your code.js getting included multiple times?cletus– cletus2009年01月26日 01:29:47 +00:00Commented Jan 26, 2009 at 1:29
-
Honesty, what you have is the JavaScript idiom for this. It's also the most readable way of doing it. No need to be too clever.Zach– Zach2009年01月26日 02:29:40 +00:00Commented Jan 26, 2009 at 2:29
3 Answers 3
var _ow = _ow || { Auth: ... };
if its already defined then it wont be defined again.
3 Comments
Are you familiar with Crockford's Javascript Module Pattern?
A slight variation on how to prevent overwriting the namespace:
var _ow;
if(!_ow) _ow = {};
2 Comments
While what you are doing will technically work, it is inefficient, because even though your code only gets run once, it does end up being parsed a number of times on some browsers (this is different than downloading a file via the network, and cannot be cached).
It is best to ensure that the script only gets included once. For all the repeated functionality you can expose a function to be called whenever needed.