I would like to send some javascript from one file to another in my own server. For example on file 1 I have the following code:
<script>
alert("Hey There!");
</script>
I want to send this code to file 2, so that the alert happens on file 2. Imagine File 2 had already loaded, I want to perform some processing on File 1 and based on the result of said processing I want to send something to File 2.
File 2 should not be sending any requests to File 1, File 1 should be doing all the sending, and File 2 should receive the message without page refresh.
Is this possible?
EDIT
Imagine I have 3 files (2 html and 1 js). File A has already loaded, there’s nothing in there. The js file is call “sayHello.js”, it has the following content:
alert('Indeed 10 is less than 100');
File B has the following content:
if (10 < 100) {
// attach the js file "sayHello.js" to File A
}
How would I be able to attach the js file to File A from File B (using the jQuery.getScript() method) and have the script execute on File A?
Generally – you have to separate in your thinking what runs where – what code runs on the server and what code runs on the browser.
In the more complicated cases – the JavaScript that runs on the client would be generated by a server page that generates relevant JavaScript in according to the request context – in this case you have to remember well the order of operations.
Taking the simple premise that you refer communication on the client between code – you should keep in mind that the files do not process anything – they load JavaScript code to the root scope of the browser, and the browser executes it.
In that manner you have to separate between commands and definitions, while every file that loads can access all the “members” that were introduced to the root scope by formerly loaded scripts (the right name is for these members is symbols, i.e – all functions and variables).
Discussing your two files –
File 2 looks like a “main” to me, and file 1 looks like a “utility/library” to me.
So, instead of executing code on the root scope on file 1 – you have to define functions – where these functions would be accessible to file 2.
Your HTML:
File 1:
File 2:
Having that in mind – I think that what you’re describing is a dynamic load of scripts to the client.
Adding a second script on the fly to the current page, using jQuery is done using
http://api.jquery.com/jQuery.getScript/
Now – for a more complex example –
Your HTML
File1.js
File2.js
EDIT:
What you need to read about is variables scope in JavaScript.
File A has the following content:
File B has the following content:
HTML has the following content: