views:

295

answers:

4

Hi,

Basically what I'm after is, following squashing all my JavaScript into one file (or a few files) how can I make a document.observe(dom:loaded({...})) function call for the right page?

So, say I have 5 pages in my website, and each one has a separate JS file. Inside each file is a load of page related functions, and a special function which sets up eventhandlers etc when the DOM has loaded. Obviously if all 5 pages include their own JS files then that's fine. But I want to compact all my JS into one page for versioning and efficiency reasons.

Therefore, in doing this, I would end up with 5 "dom:loaded" functions waiting to be setup. This won't do as the stuff inside these functions is page specific. So, my question is how can I do what I want to do without causing a whole bunch of DOM errors, and false eventhandler setup requests?

Ive considered namespaces and stuff like that but don't really know anything about it/them.

Btw, I'm using the Prototype lib. Oh, and my sites are considerably larger than 5 pages! :)

Thanks, Lee

A: 

Some ideas: inspect the dom to identify the page. For example, attach an attribute to the body element. put a script tag in the page that sets a variable. inspect the url.

when the load event fires, the event handler identifies the page and hands control off to the proper code.

chris
Thank you for taking the time to answer. I had kinda considered those ideas but had brushed them off as a bit "hacky". I guess Im just being too fussy. Ill give them a go. Thanks
LeeRM
+1  A: 

I would give different IDs to the <body>s of the separate HTML files and test in the dom:loaded event the name of the <body> element using $$('body')[0].id.

Marcel Korpel
Thanks very much. Im going to give this a go along with Chris' suggestions above.
LeeRM
@LeeRM: you're welcome.
Marcel Korpel
A: 

I have opted to use a php regexp to capture the URI, then use this as the body ID. On my sites, where the page names are static, it means each page will have a unique ID.

I then include a JS file in the HEAD which contains a switch block inside which the appropriate code/functions are loaded. The switch block is inside the document.observe(dom:loaded...) function.

Works a treat!

Thank you again for your help.

LeeRM
A: 

I tend to always write my .js with no self activation (so much as possible)...

psuedo-code

namespace('mysite.section.init');
mysite.section.init.pageName = function(){
  //stuff to run here...
};

in your home page, at the bottom, or via dom:loaded event simply run mysite.section.init.pageName();

Tracker1