Sorry for the blunt question, I will try to explain further.

I am going to have a website which uses jQuery, and I feel that at some point in time, there will be A LOT of jQuery code, meaning A LOT of functions, jQuery selectors, etc. Is there a way to limit the availability of jQuery code for specific pages? Perhaps using objects? I'm looking for the best approach here so I don't just run off into a storm and can't find my way out.



I normally separate my code in a modular fashion where each part of the page (each module) gets its own file for CSS, JS and HTML (as well as PHP/whatever server side code you use).

Each module is wrapped in a div or section (or whatever's semantic) element with a unique (obviously) ID, like this:

<section id="recent-comments">

    <h2>Recent comments</h2>



Then I create a CSS file named after the module (recent-comments.css) and a JS file (recent-comments.js). The JS-file can look something like this:

Base.modules.RecentComments = {
    init: function () {
        this.autoRefreshComments(); // this is just an example

    autoRefreshComments: function () {
        setInterval(function () {
        }, 5000);

If I start writing code in a module file that I think can be re-used I usually turn it into a jQuery plug-in (that can be re-used).

This leads to plenty of different CSS and JS-files but of course I merge them all into one before serving them to the browser.

The benefit of this is that you can very quickly find code related to one part of your page and your files are normally kept pretty short and concise.

I used to serve different JS/CSS for each page (only the modules that were in use on that page) but I don't think it improves performance as it leads to one unique CSS and JS files per page instead of just one CSS and JS file that is cached on the first page load.

Edit: btw, this is what the Base "class" would look like:

var Base = {
    modules: [], 

    init: function () {

    runModules: function () {
        for (var module in Base.modules) {
            // Work out the HTML-ID based on the module-name (RecentComments == recent-comments)
            var id      = module.replace(/([A-Z])/g, '-$1').toLowerCase();
                id      = id.substring(0, 1) == '-' ? id.substring(1) : id;
            var mod     = jQuery('#' + id);

            if ( 
                    mod.length && 
                    typeof(Base.modules[module]) != 'undefined' && 
                    typeof(Base.modules[module].init) == 'function' 
            ) {


  • 1
    do you have any examples of this up on github or live sites? I get it, but not enough to put something together. I think this might be a valuable method for landing pages.
    – Shane
    Feb 12 '13 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.