Björn
Björn

Reputation: 13207

Speed improval through conditional function execution?

I have a website with multiple pages, each of them with custom event handlers attached to certain elements. Each page has an id in the html markup (#page1, #page2, ...).

In my javascript file for the website I have seperated the functions for each site in self executing modules, simplified like so:

//module 1 for stuff that happens on #page1
(function() {
    // stuff to happen, events, delegations, preparations, etc
})();

I thought I could execute certain page related modules only if the #id is found in the current document like:

if( $("#page1").length ) {
   // call module 1
};

... because a lot of event delegation happens in some modules.

Is this a common/good approach to speed up things? Or is it better to include the modules in seperated js files only on the subsites where they are needed? Or any other method/ideas?

Upvotes: 0

Views: 120

Answers (1)

RobG
RobG

Reputation: 147403

Put all the code in a single js file so it is cached. Put an id on the body or similar element, then put each module of code in a separate function. Then have an object to hold module references linked to body element ids, then in the onload:

var modules = {
   id1: function() { /* stuff for page 1 */},
   id2: function() { /* stuff for page 2 */},
   ...
}
var id = document.body.id
if (id && id in modules) {
  modules[id]();
}

Then you just give the body the id of the function that should run for that page.

Upvotes: 5

Related Questions