In a general sense, for medium/big projects, what's the best way to handle javascript/ajax code?

Is it better, to have a script file where to put each script or, to add the script directly into the html file between tags?

I know it doesn't make any difference in terms of result, but i would like to understand what's is easier to mantain in long terms.


2 Answers 2


To put it in the html file is a very bad approach and will give you a bad headache sooner or later. To start with it would make it impossible to handle code shared between multiple pages.

I think a good way is to have one js file for every main html file, another one for every main functional group and one or more for the whole project. For example if you do complicated stuff with tables all over the site then your table.js would grow large enough to become a file of its own.

Your deployment process should then create one javascript file out of those files and minify it (or at most a very small number of files). This is important for page load performance. A good web framework should be able to do this without too much overhead.


In my opion it's always easier to maintain a seperation between html, css and javascript, and keep everything in seperate files.

As for handling ajax, I often write code as object literals and create an ajax method that is easy to use, and where there is a similar method on the serverside that parses whatever I decide to send etc.

var main = {
    init: function() { // do stuff on page init
    events: function() { // bind event handlers
        var self = this;

        $('#element').on('click', function() {
             var value = $('input.search').val();

             self.ajax('search', value).done(function(data) {
        return self;
    render: function() {
        $('body').append('some elements').fadeIn(1000);
    ajax: function(type, value) {
        return $.ajax({
             url : '/controller/ajax/',
             data: {type:type, value:value}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.