views:

404

answers:

3

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?

+2  A: 
var _ow = _ow || { Auth: ... };

if its already defined then it wont be defined again.

geowa4
Yes I was doing something like that, but then I would need to do that for all my "functions", like _ow.Auth = _ow.Auth || (function(){})(); which isn't exactly nice.
Luca Matteis
you only have to do it once for _ow
geowa4
you don't have to do it multiple times for each function, just once with you create the _ow variable
geowa4
+1  A: 

Are you familiar with Crockford's Javascript Module Pattern?

A slight variation on how to prevent overwriting the namespace:

var _ow;
if(!_ow) _ow = {};
Abie
How would that code snippet work? When re-executing that piece of code it will re-define **_ow** everytime.
Luca Matteis
leave off the var _ow;
geowa4
var _ow = 9; var _ow; assert(_ow === 9) //true
Zach
+1  A: 

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.

levik