<script id="s1" src="foo.js"></script>
<script>
alert('foo.js contains' + _source_code_of('s1'))
</script>
Can _source_code_of
be implemented?
The src attribute specifies the URL of an external script file. If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again.
For most browsers, to view inline JavaScript in the HTML source code, do one of the following. Press the Ctrl + U keyboard shortcut. Right-click an empty area on the web page and select the View page source or similar option in the pop-up menu.
Reference the External Script File A <script> tag can also be used to include an external script file to an HTML web page by using the src attribute. If you don't want to write inline JavaScript code in the <script></script> tag, then you can also write JavaScript code in a separate file with .
No, this would allow to retrieve the contents of any URL, which would break some security policies. (This would be an equivalent of an ajax get request without same-domain checks.)
However, since foo.js
is on the same domain than the page you can fetch it with an ajax request. Example with jQuery:
$.get('foo.js', function(source_code) {
alert('foo.js contains ' + source_code);
});
No, not directly for fundamental security reasons.
The fact that you've tagged this with Ajax implies that you're trying to use this as a way to retrieve data. If so, the closest similar approach is JSONP, in which the newly loaded script invokes a method to pass data back to the parent document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With