2

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?

asked Jan 26, 2009 at 1:17
2
  • Um... why is your code.js getting included multiple times? Commented 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. Commented Jan 26, 2009 at 2:29

3 Answers 3

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

if its already defined then it wont be defined again.

answered Jan 26, 2009 at 1:22
Sign up to request clarification or add additional context in comments.

3 Comments

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.
you only have to do it once for _ow
you don't have to do it multiple times for each function, just once with you create the _ow variable
1

Are you familiar with Crockford's Javascript Module Pattern?

A slight variation on how to prevent overwriting the namespace:

var _ow;
if(!_ow) _ow = {};
answered Jan 26, 2009 at 2:58

2 Comments

How would that code snippet work? When re-executing that piece of code it will re-define _ow everytime.
var _ow = 9; var _ow; assert(_ow === 9) //true
1

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.

answered Jan 26, 2009 at 4:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.