Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, What's Best, Have All the Binds in One Single File For an Entire Site or on a per Page Basis?

Tags:

I'm in the middle of building a web app with heavy use of jQuery plugins and lots of bindings.

The backend was developed with a template system which only allows (as of now) to place all scripts in that one HTML file. We will use YUI compressor to merge all these into one.

Now, for bindings, how bad is it to have binds in an HTML file (which now is a template for the whole site) for elements that may not be present on a particular page?

Any advice is greatly appreciated

like image 588
Sam3k Avatar asked Feb 11 '10 15:02

Sam3k


2 Answers

I've been using Paul Irish's markup-based solution pretty extensively on larger sites.

like image 57
Mark Hurd Avatar answered Oct 03 '22 18:10

Mark Hurd


One of the biggest problems with doing this is one of performance - the selector will be evaluated and the DOM searched for each binding not intended for a specific page. At the very least, perhaps set up an object literal to run appropriate ready binding code based on a page identifier, which could be the window.location.href or a substring of. Something like

// avoid global pollution!
(function() {

    var pages = {

        pageX : {

            ready: function() { /* code to run on ready */ },
            teardown: function() { /* code to run on teardown */ }

        },

        pageY : {

            ready: function() { /* code to run on ready */ },
            teardown: function() { /* code to run on teardown */ }

        },

    }

    // set up ready event handler 
    $(ready);

    // handler function to execute when ready event raised
    // Note: Access to pages through closure
    function ready() {
        var location = window.location.href;
        pages[location].ready();
    }

})();
like image 26
Russ Cam Avatar answered Oct 03 '22 18:10

Russ Cam