Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25237

Javascript - Get a function's name as a string

So I am including certain library like this

var start = function() { ... }

var loadScript = function() {
    script      = document.createElement('script');
    script.type = 'text/javascript';
    script.src  = 'https://whatever.com/js?callback=start';
    document.body.appendChild(script)
}

window.onload = loadScript;

As you see, I set a function called "start" as callback for the library. The trouble is that if I minify the file, the function isn't called start anymore.

I tried this, but it does not work.

    script.src  = 'https://whatever.com/js?callback=' + start.name;

How can I programatically add the name of the function to the src attribute?

EDIT

I am using Rails 4, and the assets are in Coffeescript, so I do not think I can use named function declarations.

Upvotes: 1

Views: 71

Answers (2)

ashokd
ashokd

Reputation: 393

You can do like this and it will work with any minifier.

var start = function() { ... }
var someObj = {'start': start};

Then Use someObj['start']() to call your start function.

Upvotes: 0

ded
ded

Reputation: 1330

Most minifiers won't collapse global pointers. So if you had window.start (although not super recommended to have too many generic global names like that).

Or, to justify it, window.MyAPP.Myutil.start

Another thing to keep in mind is that anonymous functions don't have name properties, even though you've assigned it to a variable. You'll need to add it to the function declaration.

window.start = function start() {
  // stuff
}

Upvotes: 1

Related Questions