1

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.

6
  • 1
    Because of the way you're declaring your functions, they really never have names. Assigning a function reference to a variable does not give a function a name. Commented Jul 17, 2015 at 16:24
  • That said, your minifier should have a way of marking a symbol as being "exported" or something like that. How are you minifying? edit - yes true; I was just being needlessly pedantic :) Commented Jul 17, 2015 at 16:26
  • Where did you set start.name? Commented Jul 17, 2015 at 16:26
  • can you show example library code org and min? Commented Jul 17, 2015 at 16:27
  • What is your minifier? Commented Jul 17, 2015 at 16:29

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

I am using Rails, and the asset are in Coffeescript, so Im not sure if I can write named function declarations
If the function has to be used for a JSONP callback, it has to be global anyway.
@Pointy is right. Which in that case, just make it an actual global by assigning it to the window.
I understand! I thought it was global, but Coffeescript gave it its own scope. Thanks!
0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.