One JS File for Multiple Pages [closed]

I like Paul Irish’s approach… you don’t have to follow it exactly, but the general idea is a very solid one.

It might look something like this for your example

Html

<body id="share">

Your page specific javascript

YourNamespace = {
  share : {
    init : function(){
      // Place the logic pertaining to the page with ID 'share' here...
    }
  }
}

Paul Irish’s Javascript that makes the magic happen

UTIL = { 
  fire : function(func,funcname, args){
    var namespace = YourNamespace;  // indicate your obj literal namespace here

    funcname = (funcname === undefined) ? 'init' : funcname;
    if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function'){
      namespace[func][funcname](args);
    }
  }, 

  loadEvents : function(){
    var bodyId = document.body.id;

    // hit up common first.
    UTIL.fire('common');

    // do all the classes too.
    $.each(document.body.className.split(/\s+/),function(i,classnm){
      UTIL.fire(classnm);
      UTIL.fire(classnm,bodyId);
    });

    UTIL.fire('common','finalize');
  }
};

// kick it all off here 
$(document).ready(UTIL.loadEvents);

So the line you see directly above will kick off the following

YourNamespace.common.init()
YourNamespace.share.init()
YourNamespace.common.finalize()

Have a read of his blog post and a few of the variations linked from it.

Leave a Comment