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.
if you want the contents of the src attribute, you would have to do an ajax request and look at the responsetext. If you where to have the js between and you could access it through innerHTML.
This might be of interest: http://ejohn.org/blog/degrading-script-tags/
I know it's a little late but some browsers support the tag LINK
rel="import"
property.http://www.html5rocks.com/en/tutorials/webcomponents/imports/
For the rest, ajax is still the preferred way.
tl;dr script tags are not subject to CORS and same-origin-policy and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a
<script>
tag, or it would breaksame-origin-policy
.long version: Most of the other answers (and the accepted answer) indicate correctly that the "correct" way to get the text content of a javascript file inserted via a
<script>
loaded into the page, is using an XMLHttpRequest to perform another seperate additional request for the resource indicated in the scriptssrc
property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the<script src=[url]></script>
would break theCORS
policies, e.g. modern browsers prevent the XHR of resources that do not provide the Access-Control-Allow-Origin header, hence browsers do not allow any other way than those subject toCORS
, to get the content.With the following code (as mentioned in the other questions "use XHR/AJAX") it is possible to do another request for all not inline script tags in the document.
and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat