Maybe it is a silly question but I am a very confused with JavaScript. I follow this code organisation with as much as possible unobtrusive JavaScript. I build a website in Ruby on Rails that uses Google Maps.
My scenario: Suppose I have a REALLY enormous website in which, in different pages, I need to initiate JavaScript scripts which do some actions.
A problem is that I have to add ALL the JavaScript code of my website to the user's browser regardless of which page the user visits. For instance, let's say I have page A which uses enormous JavaScript code and page B which uses some tiny JavaScript code. As far as I understand, in page B the user will have to retrieve ALL the JavaScript code (that is, for both pages A and B). Isn't that a little impractical?
What is more, for both pages, JavaScript is initiated by document.addEventListener("DOMContentLoaded", function, false);
function. However, the function of page A supposes that there is a div named "pageA" (which uses as a reference in order to modify it or add elements through js scripts) and similarly the function of page B supposes that there is a div named "pageB". Hence, when I am on page B I receive js error that there is no element of "pageA". How can I avoid that ?
Given the fact that, for every single page I have to load the user with my whole JavaScript code (that is for all pages) how can I initiate(that is, to start immediately when page loads and not after a user event happens) page specific JavaScript code without any such errors? I am really confused!
Wooho very fast responses thanx guys! But I never said I write the whole js code in 1 single file. Instead I uses RoR's organisation! (which btw combines all files into one single file). To clarify my problem, in different files I initiate events for page A and events for page B (or C etc..). The code fires as soon as DOMContentLoaded event happens. However when the user is on page B I don't want to fire the events for page A. Or similarly, I want to load only js for page B (so that no event for page A fires). How can I do that?
PS: If you think a better title, feel free to suggest it!