Small website - global style / format / javascript file template - improving maintainability

I often create (and inherit) small and medium sites where I have the following kind of code in a single file (usually called global.js or application.js or projectname.js).

If the functions become large, I usually put them in a separate file and call them at the bottom of the file in the section below $(document).ready().

If I have several functions that are unique to certain pages, I usually have another switch statement for the body class inside the section $(document).ready().

How could I rebuild this code to make it more convenient?

Note . I am less interested in internal functions, especially the structure and methods of using various types of functions.

I also posted the code here http://pastie.org/999932 in case this makes it easier

var ProjectNameEnvironment = {};


function someFunctionUniqueToTheHomepageNotWorthMakingConfigurable () {   
    $('.foo').hide();
    $('.bar').click(function(){
        $('.foo').show();
    });

}

function functionThatIsWorthMakingConfigurable(config) {
    var foo = config.foo || 700;
    var bar = 200;
    return foo * bar;
}


function globallyRequiredJqueryPluginTrigger (tooltip_string) {

    var tooltipTrigger = $(tooltip_string); 

    tooltipTrigger.tooltip({ 
        showURL: false
            ... 
    });
}

function minorUtilityOneLiner (selector) {
    $(selector).find('li:even').not('li ul li').addClass('even');    
}

var Lightbox = {};

Lightbox.setup = function(){
    $('li#foo a').attr('href','#alpha');
    $('li#bar a').attr('href','#beta');
}


Lightbox.init = function (config){

    if (typeof $.fn.fancybox =='function') {

        Lightbox.setup();

        var fade_in_speed = config.fade_in_speed || 1000;
        var frame_height = config.frame_height || 1700;

        $(config.selector).fancybox({ 
            frameHeight : frame_height,
            callbackOnShow: function() { 
                var content_to_load = config.content_to_load;
                    ...
            },
            callbackOnClose : function(){
                $('body').height($('body').height());
            }
        });

    } 

    else { 
        if (ProjectNameEnvironment.debug) {
            alert('the fancybox plugin has not been loaded'); 
        }
    }

}

// ---------- order of execution -----------

$(document).ready(function () {

    urls = urlConfig();

    (function globalFunctions() {

        $('.tooltip-trigger').each(function(){
            globallyRequiredJqueryPluginTrigger(this);
        });

        minorUtilityOneLiner('ul.foo')

        Lightbox.init({
            selector : 'a#a-lightbox-trigger-js',
                ...
        });

        Lightbox.init({
            selector : 'a#another-lightbox-trigger-js',
                ...
        });

    })();

    if ( $('body').attr('id') == 'home-page' ) {

        (function homeFunctions() {
             someFunctionUniqueToTheHomepageNotWorthMakingConfigurable ();
         })();

     }

});
+3
source share
3 answers

The "protected" and "high-performance" parts of your questions are so great that I am not going to consider them here :), but I will turn to maintainability.

This is the approach I use. I'm sure this can be improved - like everyone else, but so far this has worked well:

1) use namespaces. This is what I use: Is it possible to create a namespace in jQuery?

2) ( ..) ( , ..) - , . init() .

3) , , .

, , IE6 .., , , .

( namespacing, , ):

jQuery.namespace = function() {
var a=arguments, o=null, i, j, d;
for (i=0; i<a.length; i=i+1) {
    d=a[i].split(".");
    o=window;
    for (j=0; j<d.length; j=j+1) {
        o[d[j]]=o[d[j]] || {};
        o=o[d[j]];
    }
}
return o;
};

// set up your namespace
$.namespace( 'jQuery.myProject' );

// init helper
$.myProject.init = function(widget) {
    $(document).ready(widget.init);
}

/**
* Sitewide scripts
*/
$.myProject.Sitewide = {
    init: function()
    {
        $.myProject.Sitewide.doSomething();
        $.myProject.Sitewide.doSomethingElse();    
    },

    doSomething: function()
    {
        // here goes your code  
    },

    doSomethingElse: function()
    {   
        // you get the idea
    }
};

// more widgets here
// ...

// final step - call the init() helper
$.myProject.init($.myProject.Sitewide);
// init more widgets:
// $.myProject.init($.myProject.AnotherWidget);

, .

+2

, :

. . , company.js:

(function($) {

window.Company = {
    makeRed: function(elem) {
        return $(elem).css('color','red');
    },
    parseAnchors: function() {
        $('a[href="#"]').click(function(e) {
            e.preventDefault();
        });
    }
}

})(jQuery);

, , company.modal.js:

(function($) {

if (typeof Company == 'undefined') {
    return; // needs to be included after company.js
}

window.Company.modal = {
    open: function() {
        // some opening methods
    },
    close: function() {
        // some closing functions
    }
};

})(jQuery);

project.js . views, . body init:

(function($) {

window.Project = {
    init: function() {
        this.views._global.call(this);
        var classNames = document.body.className.split(" ");
        for (var i=0; classNames[i]; i++) {
            if (this.views[classNames[i]]) {
                this.views[classNames[i]].call(this);
            }
        }
     },
     views: {
         _global: function() {
             // all views
             Company.parseAnchors();
             $('a.modal').click(function() {
                 Company.modal.open();
             });
         },
         home: function() {
             // called if body classname is 'home'
             Project.addHomeStuff();
             Company.makeRed('#sale');
         }
    },
    addHomeStuff: function() {
        // some stuff to do at home
    }
};

})(jQuery);

Project.init(); body init. domReady 99,9% , . script, .

, , Company Project. . , .

, !

+1

, , , , (- Python)

def include_js(scripts):
  hash = md5(''.join(scripts))
  if not file_exists("%s/%s.js" % (path_to_js, hash))
    new_script = ""
    for file in scripts:
      new_script += file.contents
    write_file(new_script, "%s/%s.js" % (path_to_js, hash))
  return '<script type="text/js" src="%s/%s.js"></script>' % (path_to_js, hash)

:

<head>
  {% include_js(['lightbox', 'global', 'selectors', 'tooltips']) %}
</head>

.

, ,

  • js.
  • , Javascript .
  • , , . , .
  • <script>, script, .

That way, I can separate my Javascript (as well as CSS, I do the same) in separate files, but I still require the browser to make one request to get all the necessary scripts.

0
source

Source: https://habr.com/ru/post/1749475/


All Articles