If I have a script tag like this:
<script
id = "myscript"
src = "http://www.example.com/script.js"
type = "text/javascript">
</script>
I would like to get the content of the "script.js" file. I'm thinking about something like document.getElementById("myscript").text
but it doesn't work in this case.
You want to use the innerHTML property to get the contents of the script tag:
But as @olle said in another answer you probably want to have a read of: http://ejohn.org/blog/degrading-script-tags/
yes, Ajax is the way to do it, as in accepted answer. If you get down to the details, there are many pitfalls. If you use
jQuery.load(...)
, the wrong content type is assumed (html instead of application/javascript), which can mess things up by putting unwanted<br>
into your (scriptNode).innerText, and things like that. Then, if you usejQuery.getScript(...)
, the downloaded script is immediately executed, which might not be what you want (might screw up the order in which you want to load the files, in case you have several of those.)I found it best to use
jQuery.ajax
withdataType: "text"
I used this Ajax technique in a project with a frameset, where the frameset and/or several frames need the same JavaScript, in order to avoid having the server send that JavaScript multiple times.
Here is code, tested and working:
related question
If you're looking to access the attributes of the
<script>
tag rather than the contents of script.js, then XPath may well be what you're after.It will allow you to get each of the script attributes.
If it's the example.js file contents you're after, then you can fire off an AJAX request to fetch it.
.text did get you contents of the tag, it's just that you have nothing between your open tag and your end tag. You can get the src attribute of the element using .src, and then if you want to get the javascript file you would follow the link and make an ajax request for it.
You want to get the contents of the file http://www.example.com/script.js ? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.
Could you elaborate on what you're trying to accomplish?
Hopefully you are already using some JavaScript library...
What about getting the src attribute's value, the URL, and then use your library's Ajax tools to make a request to that URL and save that result wherever you are desiring to do so?
The specific details would vary depending on the library you are using.