How do I get the contents of a loaded script at runtime without using ajax to read the script from the source?
-
Could you provide a bit more detail about why you need to get the source of the script? Also are these inline scripts or included from external js files using `src=""`? – slashnick Feb 14 '12 at 09:15
-
Hi, basically if I load a script with a tag I want another javascript to read the contents of the script. But it's not the "source" i am interested in I am interested in the actual loaded script, like if I were to access any other html element like the innerHTML of a div or such. – Jonas B Feb 14 '12 at 09:18
2 Answers
if the source of the script is written inside the script tag, like so:
<script>
source comes here
</script>
then you can use the innerHTML attribute to retrieve it, but if the script is loaded with the "src" attribute then I think that you can not use the dom to get the content. i believe that your only option is to use the src attribute, and then issue an ajax request to get the source.
check this: How can I get the content of the file specified as the 'src' of a <script> tag?

- 1
- 1

- 155,636
- 47
- 315
- 299
-
Hi, thanks for the reply. Yes I'm aware that inline scripts can be easily retrieved through the innerHTML attribute, these scripts unfortunately are not inline. And ajax is not an option as I need the actual script loaded by the browser.. I'm starting to think this ain't possible though, at least not in any easy way. – Jonas B Feb 14 '12 at 09:36
-
what exactly are you trying to do? why do you need the "loaded" script? let's say you got it somehow, now what are you planing on doing with it? – Nitzan Tomer Feb 14 '12 at 09:42
-
I prefer not going into it as last time it turned into a fullblown discussion of best practises and it's to much to explain every single detail towards this aproach. I just want to know if this is technically possible otherwise i'll find another solution on my own – Jonas B Feb 14 '12 at 09:46
-
well, what happens is that the script content is being interpreted by the browser, one line at a time. some expressions are being evaluated if needed, and once that's done with what you are left with is different scopes and variables/methods in them. you can of course access all of that, but without knowing what you're looking for it's hard to guide you in the right direction (or tell you if it's even possible) – Nitzan Tomer Feb 14 '12 at 10:00
I think if you actually want the text of the loaded script you need to request it with ajax rather than a script tag. That way you can inspect the response as text and eval
it if you need to. If using jQuery you can use jQuery.getScript.
I'm still not entirely sure why you need to access the source, it would be cleaner to form the script you are loading as an object with fields you can query from the second script, rather than reading the source.

- 26,167
- 10
- 55
- 67