Even Smaller
This is a follow-up to Replace MicrosoftMvcAjax.js.
I combined the handle and click functions into a single function declaration. That allowed me to reduce two functions into one and remove two convenience functions. I also modified the error and complete callbacks to return the status code instead of the less granular “error” or “success”. Here’s the new version:
mvcAjax = {};
mvcAjax.submit = mvcAjax.click = function(element, event, options)
{
if (!event)
event = window.event;
if (event)
$.event.fix(event).preventDefault();
element = $(element).eq(0);
isForm = element.is("form");
$.ajax
(
{
type: "POST",
url: element.attr(isForm ? "action" : "href"),
data: isForm ? element.serialize() : {},
success: function(data)
{
if (options.onSuccess)
options.onSuccess(data);
},
error: function(request)
{
if (options.onError)
options.onError(request.status);
},
complete: function(request)
{
if (options.onComplete)
options.onComplete(request.status);
},
dataType: options.json ? "json" : undefined
}
);
};
And here’s the 408 byte (0.39% of the original 104,228 bytes) obfuscated and minified version:
mvcAjax={};mvcAjax.submit=mvcAjax.click=function(a,b,c){if(!b)b=window.event;b&&$.event.fix(b).preventDefault();a=$(a).eq(0);d=a.is("form");$.ajax({type:"POST",url:a.attr(d?"action":"href"),data:d?a.serialize():{},success:function(a){c.onSuccess&&c.onSuccess(a)},error:function(a){c.onError&&c.onError(a.status)},complete:function(a){c.onComplete&&c.onComplete(a.status)},dataType:c.json?"json":undefined})};
Google’s new Closure Tools helped identify a few additional optimizations.
For example:
if (flag)
{
doSomething();
}
can be reduced to:
flag && doSomething();
You can download and compile the tools yourself or, more conveniently, use the web UI version.