Call a function in one Javascript file from another Javascript file?

I need to call a function in an external .js file from another .js file without referencing the external file in the <head> .

I know that you can dynamically add an external ".js" file to access this file, I can do it like this ...

 var AppFile = "test/testApp_1.js"; var NewScript=document.createElement('script'); var headID = document.getElementsByTagName("head")[0]; NewScript.src = AppFile; headID.appendChild(NewScript); 

But...

this is useless to me, since external files must be standalone files that run the startup procedures ...

 $(document).ready(function() {...} 

therefore, adding a complete file dynamically has an undesirable affect. In addition, I cannot pre-reference the external file in the <head> , since it must be dynamic. So this external file "test/testApp_1.js" contains a function that returns a string variable ...

 function setAppLogo(){ var LogoFile = "test/TestApp_1_Logo.png"; return LogoFile; } 

I need access to this function, or I could store the string as a global var in an external file ... this is normal anyway, I just need access to the value in the LogoFile without loading the entire external file.

This man silenced me for several hours, so any ideas would be greatly appreciated.

+7
source share
6 answers

It may be useful for you to have some kind of app.js file that contains global variables / values ​​that you want to use from a lot of places. You should include this .js file on every page (and possibly minimize / combine it with other js if you want to be smart and improve performance). As a rule, these global bindings should be bound to some object that you create, for example, var APPNAME = { }; with variables / functions on it to be used from many places.

After that, the external ".js" file that you want to download, and the one you are currently using, can simultaneously access the global variable APPNAME and all its attributes / functions and use them as desired. This may be the best approach to make your javascript more modular and shared. Hope this helps.

+1
source

You want to download the file after loading jQuery using ajax and then run the associated script in a successful ajax function.

See jQuery getScript function: http://api.jquery.com/jQuery.getScript/

 $(document).ready(function(){ $.getScript("http://domain.com/ajax/test.js", function(data, textStatus, jqxhr) { console.log(data); //data returned console.log(textStatus); //success console.log(jqxhr.status); //200 console.log('Load was performed.'); //run your second script executable code here }); }); 
0
source

You can load the entire script through XHR (e.g. $. Get in jQuery ) and then parse it, possibly using a regular expression to extract the part you need:

 $.get('pathtoscript.js', function(scriptBody) { var regex = /function\s+setUpLogo\(\)\s*\{[^}]+}/g; alert(scriptBody.match(regex)[0]); // supposed to output a function called // 'setUpLogo' from the script, if the // function does not have {} blocks inside }); 

However, it should be noted that this approach is likely to cause service barriers. Regular expressions are not the best tool for analyzing JavaScript code; the example above, for example, will not analyze functions with nested {} blocks, which may well exist in the code in question.

You may need to find a solution to the problem on the server side, for example. Adding the necessary script path or its part before sending the page to the browser.

0
source

I'm not sure if this is a good idea, but you can create an iframe and eval file inside its window object to avoid most of the unwanted side effects (assuming it doesn't try to access its parent element). Then you can access any function / variable you want through an iframe window object.

Example:

 function loadSomeJsInAFrame(url,cb) { jQuery.get(url,function(res) { iframe = jQuery('<iframe></iframe>').hide().appendTo(document.body); iframe[0].contentWindow.eval(res); if(cb) cb(iframe[0].contentWindow); },'text'); } loadSomeJsInAFrame('test/testApp_1.js',function(frameWindow) { console.log(frameWindow.setAppLogo()); jQuery(frameWindow.frameElement).remove(); }); 

This does not guarantee that the sript in the file cannot interact with your document, but it is unlikely to come from a reliable source.

Also, be sure to remove your iframe after you get what you need.

0
source

Well, thanks to everyone for the input, but I think that what I'm trying to do is currently not possible, that is, access to the function from another file without loading this file. However, I found a solution to my problem. Now I ask my server for a list of available applications, then I use this list to dynamically create applications in the user interface. when choosing an application, then I can call this file and functions inside. Its a bit more complicated, but its agility, good performance, and it works. Thanks again for brainstorming!;)

0
source

Perhaps using Web Workers . You could run your script, which you would like to enter as an isolated environment, so it will not ruin your current page.

As you said, it is possible that setAppLogo will be global inside "test/testApp_1.js" , so I will rely on this statement.

In the original script, you must create a working one that references the working script file and listen for the messages that will be received from the working one:

 var worker = new Worker('worker.js'); worker.onmessage = function (e) { // .... }; 

Then, in the worker ( worker.js ), you can use the special function importScripts ( docs ), which allows you to load external scripts in the worker, the worker can also see the global variables of these scripts. There is also a postMessage function, available in working order to send user messages back to the original script, which in turn listens for these messages ( worker.onmessage ). Code for worker.js :

 importScripts('test/testApp_1.js'); // "setAppLogo" is now available to worker as it is global in 'test/testApp_1.js' // use Worker API to send message back to original script postMessage(setAppLogo()); 

When called, you will get the result of setAppLogo in the listener:

 worker.onmessage = function (e) { console.log(e.data); // "test/TestApp_1_Logo.png" }; 

This example is very simple, but you should learn more about the web workers API and possible errors.

0
source

All Articles