Alex Rivera | Logout

One JS File for Multiple Pages

Asked 2011-12-07T04:10:48.097
54

I typically put all the JavaScript scripts into one file e.g. scripts.js (the less HTTP request, the better). So, as expected, some scripts are needed for some pages, some aren't.

To target a specific page, I use something like:

if ($("body#share").length > 0) {
    // Place the logic pertaining to the page with ID 'share' here...
}

// The file / script continues...

Other or better suggestions? Thanks!

Clarification: I was not looking for the pros / cons between consolidating multiple JS files into one big file and keeping multiple separate JS files. The answer for this is surely 'depends on the situation' (we know that). My question is, assuming all my JS logic is placed into one big file, how do I make a particular (chunk of) script runs only when the corresponding page is loaded? One way I used to do is using if ($('#id-of-target-element')) { /* run the script */}; is there a better way?

Edit
Report

1 Answer

4

Ok. Lets hope, code example will say it better, than wall of text:


your one-and-only.js file:

var MY_SITE = {
    // you have one namespace-object where you hold all your stuff
    main_page: {
        // inside you have smaller chunks, for specific pages or widgets
        // this one is for main page
        _init: function () {
        ... 
        },
        ... 
        showSplashScreen: function () {
        ...
        }      
    },
    ... 
    // but there are other pages
    contacts: { ... },
    // or widgets
    cool_menu: { ... },
    // and maybe you want to put common functions into dedicated block
    global_utilities: { ... },
    // and of course - the loader
    _start: function () {
        // here we simply call one _init of the page module that was specified 
        this[PAGE_TYPE]._init(); 
        // and more tricky stuff - we can search the page for elements
        // that contain special data-attribute, collect them
        var widgets = $('[data-our-widget]').each().getAttributeValue( 'data-or-widget' );
       // and then _init each of those widgets just like we did with main page 
        widgets.forEach( function (v) {
            this[v]._init();
        }
    }
};
document.on('ready', MY_SITE.start); // here we assume some random js framework

your <script> tags on the page:

<script>var PAGE_TYPE = 'main_page';</script>
<script src="one-and-only.js" />

your 'magic' elements on the page:

<div id="whatever" data-our-widget="cool_menu"> ... </div>

Disclaimer: This is high level overview! Implementation details may and should vary, depending on your needs.

answered 2012-01-29T00:07:43.377

Your Answer