views:

45

answers:

1

Hi, I have the following prototype JavaScript code

Event.observe( window, 'load', function() {
    Event.observe( 'agreement', 'click', function() { alert("It works") });
});

It is used on only one page of my site, what is the best way to organise it?

I suppose I could put it in its own file, and include it only on that page. Or I could add it to one big file which is loaded for the whole site, but I tried doing that, and got an error because the element "agreement" does not exist on all pages.

+2  A: 

If you do move it into its own file that is referenced on all site pages, why not just test for the existence of the #agreement element before adding the click event handler:

Event.observe( window, 'load', function() {
    if($('#agreement') != null){
        Event.observe( 'agreement', 'click', function() { alert("It works") });
    }
});

That being said, if it's only ever going to be used on that one page of your site, I would leave it as inline javascript as it's one less request the browser has to make for a resource.

But (there's always a but) the above can lead to projects that are difficult to maintain since you can end up with a lot of inline javascript sprinkled through your markup.

Pat