Hi, I have several pages that load the same javascript function on the same page. I'm looking for a way to load them without have to rename the function. I know in php you can determine if a function already exists. Does javascript have a similar method to see if the function has already been loaded?
er, yes. 'typeof': <script type="text/javascript"> alert(typeof(mouseup)); // undefined var mouseup = function(e) { document.onmousemove=null; } alert(typeof(mouseup)); // alerts 'function' - you can compare against this etc. </script> PHP: one thing to keep in mind. in javascript, you can overwrite ANY name space, including the ECMA built-in functions - for example, consider this: <script type="text/javascript"> alert(typeof(alert)); var alert = function(e) { document.write(e + "<br />"); } alert(typeof(alert)); var alert = "hello!"; document.write(typeof(alert)); </script> PHP: it will output: function function string but the way alerts happen from the 2-nd one down is via the new document.write. there is no danger in redefining the functions - except when this may leave circular references to dom objects - you may get memory leaks - but you will have gotten them anyway under such conditions so...
If you use an object as a container for your functions, you can just check for the existance of the object. var toolbox = new Object(); toolbox.tool_a = function(a, b) { alert(a + b); } Code (markup): if( ! toolbox) { load('toolbox.js'); } Code (markup):
heh that kind of namespacing is cool - but what if toolbox has more methods and you need to check for a specific one only, i.e. : var toolbox = { tool_a = function(a, b) { alert(a + b); }, tool_b = function(a, b) { alert(a - b); } }; // then this... if(!toolbox) { // do something. } // ... is not specific to a tool_a or tool_b and would evaluate as false only if no functions are defined and true if either. // you'd have to make a new object for each function... toolbox.tool_b = function() { alert("hi!"); }; PHP:
Then you don't sub-namespace it, you declare it in the global/window namespace and check for it there. if( ! window.my_func) { } Code (markup):