Question

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?

Was it helpful?

Solution

Are you familiar with Crockford's Javascript Module Pattern?

A slight variation on how to prevent overwriting the namespace:

var _ow;
if(!_ow) _ow = {};

OTHER TIPS

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

if its already defined then it wont be defined again.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top