views:

231

answers:

2

Hi,

My webpage with diffrent sites should just load one .js file for cache optimizing. The problem comes up, when the file is loaded. It applies the listener on every page to the form elements (for example) so, just the last page's form acts like it should, the others does not cause their actions were overwritten.

So my question, how can I say the script that it schould apply just the for this site importent listeners.

I am using the jQuery framework.

A: 

Wrap each page in different divs with a simple id like "page1" and "page2". Then in your javascript grab the elements with the ids:

$('#page1 div').show();
$('#page2 div').hide();

This will show all the divs on page1 and hide them all on page2.

smack0007
not really sexy though...
Thomaschaaf
+2  A: 

Your attempt at optimizing for the browser is conflicting w/ your varying page-by-page behavior. I wouldn't jam it all into one js file. Think about maintainability, modularization.

You could put common/shared code into one js file, and include it in all pages. The browser will still cache it all, it will just have to make an extra request if only to check if was modified since the last time it fetched it. But at least your sanity will still be in check.

But anyway, here's the answer:

Page 1:

<body id="page1">...</body>

Page 2:

<body id="page2">...</body>

etc. Now in monster.js when you are attaching your behavior to page 1:

$(document).ready(function() {
    if(this.body.id != 'page1')
        return;

    // proceed as before
})

Same for the section attaching behavior to page 2 elements:

$(document).ready(function() {
    if(this.body.id != 'page2')
        return;

    // proceed as before
})

etc

Crescent Fresh