Alex Rivera | Logout

A question about referencing functions in Javascript

Asked 2009-06-01T20:22:17.307
12

The problem: I have a jQuery heavy page that has a built in admin interface. The admin functions only trigger when an admin variable is set. These functions require a second library to work properly and the second file is only included if the user is an admin when the page is first created. The functions will never trigger for normal users and normal users do not get the include for the second library.

Is it bad to reference a function does not exist in the files currently included even if that function can never be called? (does that make sense :)

Pseudocode:

header: (notice that admin.js is not included)

<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="user.js"></script>

script.js: (admin functions referenced but can't be executed)

admin = false; // Assume this

$(".something").dblclick(function(){
 if(admin)
  adminstuff(); // Implemented in admin.js (not included)
 else
  userstuff();
});

Ideas: I suppose two separate files for users and admins could be used but I feel that would be an overly complicated solution (don't want to maintain two large files with only a few lines of difference). The only reason I include a reference to the admin function in this file is I need to attach it to page elements that get refreshed as a part of the script. When jQuery refreshes the page I need to reattach function to interactive elements.

The Question: I want to keep things very simple and not have to include file I don't have to if they will not be used by the user. Is this a good way to do this or should I be going another route?

Edit
Report

2 Answers

3

Good question. It shouldn't cause any JavaScript problems.

Other things to consider: you are potentially exposing your admin capabilities to the world when you do this, which might be useful to hackers. That's probably not much of a concern, but it is something to be aware of.

See also:

Why can I use a function before it’s defined in Javascript?

answered 2009-06-01T20:29:56.997
1

Javascript is dynamic - it shouldn't care if the functions aren't defined.

If you put your admin functions in a namespace object (probably a good practice anyway), you have a couple of options.

  1. Check for the existence of the function in the admin object
  2. Check for the existence of the admin object (possibly replacing your flag)
  3. Have an operations object instead, where the admin file replaces select functions when it loads. (Even better, use prototypical inheritance to hide them.)
answered 2009-06-01T20:44:07.217

Your Answer