Frayt
Frayt

Reputation: 1233

Javascript minifier removes function

I have a JS file that I am trying to minify but it is having some trouble. Here is the file:

$(document).ready(function () {
function DisplayMessage(message, iserror) {
    var htmlclass = iserror ? "error" : "success";

    $('div.response-message').empty()
        .append(message)
        .addClass(htmlclass);

    $('div.response-message').animate({
        top: "-1px"
    }, 1000, function () {
        alert("donee");
    });
}

$('.account-overlay-link > a.link').click(function (e) {
    e.preventDefault();
    $('.account-overlay.background').removeClass("hide");
});

$('.account-overlay > .area > .close').click(function (e) {
    e.preventDefault();
    $('.account-overlay.background').addClass("hide");
});
});

As you can see I have a regular javascript function at the top and two jQuery event handlers below. When I save the file to minify, the minified file contains the two jQuery handlers but the function is nowhere to be seen.

Strangely, if I remove the two jQuery blocks but leave the function in, the file still minifies, but it is blank (apart from the (document).ready) as if the function does not exist.

I have tried recreating the file, restarting Visual Studios, but nothing is working...

Upvotes: 2

Views: 635

Answers (2)

Frithjof Schaefer
Frithjof Schaefer

Reputation: 1205

Another thing to keep in mind is that some minifiers cannot deal with "special" keywords...

Consider to check your Code if it contains "fancy" stuff like

  • let, const
  • special loops like for(var a of myData)
  • special checks such as if("MyProperty" in myObject)

At least in my case, this was the real problem

Upvotes: 0

Pointy
Pointy

Reputation: 413976

Your function is not called by any code inside the "ready" handler function, so it's being eliminated as dead code. Nothing from outside the handler would be able to call it anyway.

If you want the function to be a globally-visible symbol, you'll have to explicitly assign it to a property of the window object:

$(document).ready(function () {
function DisplayMessage(message, iserror) {
    var htmlclass = iserror ? "error" : "success";

    $('div.response-message').empty()
        .append(message)
        .addClass(htmlclass);

    $('div.response-message').animate({
        top: "-1px"
    }, 1000, function () {
        alert("donee");
    });
}
window.DisplayMessage = DisplayMessage;

If you do that, the minifier won't remove it.

Upvotes: 5

Related Questions