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 for a specific site (#page1 or #page2 or ...)
})();

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?

newest questions tagged jquery – Stack Overflow

About Admin