views:

38

answers:

3

I have a relatively large (in terms of memory use and code size) JS function (running in IE/FF) that I use only occassionally (like, a couple of times per day). I think I can get rid of it when I'm done with it by nulling out its function (using the variable name of the 'function object', as it were).

I am fuzzy though on how I would get it back, supposing maybe some time later I wanted to do it again. How would I load JS on the fly from a URL like the 'script' tag does?

Does this whole line of reasoning make sense?

A: 

It's a tad hacky, but there are two ways:

Use DOM methods to insert a script tag into the page to a file that has that function in it. You might need to add a query string so that it thinks it's a new javascript file (like function.js?(random number))

Use AJAX to download the file with the function and eval(); it

Jeffrey Aylesworth
For the love of all things good, do not `eval` it. What if the script unexpectedly 404's and returns an error page with some JavaScript in it? Expect a load of errors and nasty XSS vulnerabilities to follow if you use that route...
Nathan Kleyn
A: 

The only real way to do this is to insert a script element into the document dynamically using JavaScript with a link to a script file containing your function, causing the script to be loaded. One caveat: you must make sure that the filename has the time appended as a query string, otherwise cache unfriendly browsers like Internet Explorer will not reload the script again.

Nathan Kleyn
A: 

Like others have said, the best bet is to go ahead and insert a new script tag into the page with some kind of query parameter to avoid caching issues. If you're using a JS Library, this technique is actually called "JSONP"; jQuery in particular has a nice method for doing this that gives you an easy way to attach a callback function and such. If you write your own native version, you'll need to watch the readystate of the new script node to know when it's actually loaded.

That said, one thing I'm curious about - and anyone else, please correct me if I'm wrong - why not use the "delete" keyword to kill your function, instead of nulling it out? Something like...

function myFunction() { return; }

Then...

delete myFunction;

Seems to be a more efficient way of cleaning things up, at least from my perspective.

Ryan McGrath
delete myFunction leaves the function intact. Trying to delete it returns false, meaning a function Object can't be deleted this way.
KooiInc